rand() 函數後繼續指令的問題 (Problem with continue instruction after rand() function)


問題描述

rand() 函數後繼續指令的問題 (Problem with continue instruction after rand() function)

我只是想解決一個要求我編寫一個例程來生成一組介於 2 到 10 之間的偶數隨機數的練習。

問題是在打印時,因為我不希望最後一個數字後跟一個逗號。

這是我的代碼:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    int i, a, b, c;

    i = a = b = c = 0;

    srand(time(NULL));

    for (i = 2; i <= 10; i++)
    {
        a = rand() % 8 + 2;

        if ((i <= 10) && (a % 2) != 0)
        {   
            continue;
        }
        printf((i < 10) ? "%d, " : "%d\n", a);
    }
    return 0;
}

這是兩個執行示例:

4, 4, 2, 8,
2, 8, 6, 4, 2

其中一個逗號沒有出現在最後,但在另一個它確實。在調試時,我發現當最後一個數字為奇數時會發生錯誤,因為 continue 語句會導致它進入下一次迭代。


參考解法

方法 1:

As Retired Ninja has said, there are many unnecessary conditionals that can be avoided. I have revised your code so that a will always generate an even number between 2 and 10, thereby removing the need for the logic you implemented. This is what I have assigned this new a value as:

a = ((rand() % 4) * 2 + 2);

This generates a random value between [0,4], multiplies it by 2, and adds 2, for an integer between 2 and 10, noninclusive. Since your new a is always even, I removed your logic to check whether the number is even.

Revised code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    int i, a, b, c;

    i = a = b = c = 0;

    srand(time(NULL));

    for (i = 2; i <= 10; i++)
    {
        a = ((rand() % 4) * 2 + 2);
        printf((i < 10) ? "%d, " : "%d\n", a);
    }
    return 0;
}

Note that this code will always produce 9 numbers, as you have not specified how many values to print each time, just that you need to "write a routine to generate a set of even random numbers between 2 to 10". You can always change the amount of numbers printed by changing the value of i in the for loop. The comma issue, however, is not a problem anymore.

If my solution has helped you, please mark my answer as the correct answer :)

(by Juan Jqwert9988)

參考文件

  1. Problem with continue instruction after rand() function (CC BY‑SA 2.5/3.0/4.0)

#continue #conditional-statements #C #random






相關問題

skrip shell: loop bersarang dan lanjutkan (shell script : nested loop and continue)

syntaxError:“繼續”在循環中不正確 (syntaxError: 'continue' not properly in loop)

php continue - 替代方式? (php continue - alternative way?)

Python 中的歐拉 #4 (Euler #4 in Python)

if-continue vs 嵌套 if (if-continue vs nested if)

如何返回上一個 while 循環? (How do I return to the previous while loop?)

php foreach 繼續 (php foreach continue)

在while循環中繼續的奇怪行為 (weird behaviour of continue in while loop)

是否可以使用 'yield' 來生成 'Iterator' 而不是 Scala 中的列表? (Is it possible to use 'yield' to generate 'Iterator' instead of a list in Scala?)

BASH:在 for 循環中使用 continue (BASH: Using a continue in a for loop)

rand() 函數後繼續指令的問題 (Problem with continue instruction after rand() function)

在tictactoe遊戲中重複輸入錯誤 (Error in repeating input in a tictactoe game)







留言討論