問題描述
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 :)