C - 随机数生成

标签 c random

这里是 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/

相关文章:

c - 从C中的BST中删除节点

python - 包括 numpy random.uniform 的上限

javascript - 使用 Bacon.js 进行随机数流

random - 为什么在 Clojure 中使用种子时不会重复生成可重现的随机数?

sql - 使用随机值作为连接条件

c - 写入文件

c - 我如何配置 Vim 以在 Windows 上使用 Borland 的编译器编译 C 代码?

c - 如何改进 Nios 2 的临时巡航控制系统?

c - 巨型迷宫的最短路径(HUGE)

Python:使用频率数据对总体进行下采样