这里是 C 语言的新手。 每次运行程序时,我都试图为变量设置不同的值。 我有这段代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ADD 1
#define SUB 2
#define MUL 3
#define DIV 4
int main(void)
{
double out;
int choice;
float x, y;
printf("Welcome to our first calculator program!\n");
printf("===========================\n");
printf("Please insert 2 numbers:\n");
scanf("%f%f", &x, &y);
choice = 1 + srand(time(NULL)) % 4;
if(choice == ADD)
out = x + y;
else if(choice == SUB)
out = x - y;
else if(choice == MUL)
out = x * y;
else
{
if(y != 0)
out = x / y;
else
{
out = 0;
fprintf(stderr, "error");
return 1;
}
}
printf("The outcome is: %0.2lf\n", out);
return 0;
}
但它总是给我 4 个选择。我不明白为什么...
你能帮帮我吗?谢谢。
最佳答案
现在您正在调用 srand
并期待一个随机数。
您应该通过调用 srand
为熵池播种,然后调用 rand
获取随机数:)
用法示例取自:http://www.cplusplus.com/reference/cstdlib/srand/
int main ()
{
printf ("First number: %d\n", rand()%100);
srand (time(NULL));
printf ("Random number: %d\n", rand()%100);
srand (1);
printf ("Again the first number: %d\n", rand()%100);
return 0;
}
通过调用 srand
查看您是如何播种的,然后从 rand
中检索随机整数
你需要这样做:
srand(time(NULL));
choice = 1 + rand() % 4;
而不是这个:
choice = 1 + srand(time(NULL)) % 4;
关于C - 随机数生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22054658/