如何为每个抗原测试生成不同的随机结果值(需使用函数实现)
修复每个抗原测试结果不同的问题
嘿,你遇到的问题根源在于每次调用testResult()都重新初始化了随机种子!
问题分析
rand()函数的随机序列是基于初始种子生成的,而srand(time(NULL))用当前秒级时间戳作为种子。因为你的循环执行速度极快,在同一秒内多次调用testResult()时,time(NULL)返回的数值完全相同,导致每次rand()都从同一个起点生成序列,自然返回的0/1结果也一模一样。
另外你的main()里还重复调用了一次srand(time(NULL)),这也是多余的,随机种子只需要初始化一次就够了。
修改后的代码
#include<stdio.h> #include<time.h> #include<stdlib.h> // 先声明函数(或者把函数定义移到main前,避免声明) int testResult(); float positivePercentage(int, int); void displayResults(int,int,float); int main() { // 只在这里初始化一次随机种子! srand(time(NULL)); int result; int i; int negativeResult = 0; int positiveResult = 0; int numofTests; numofTests = 1 + (int)rand() % 100; printf("You have completed %d test today, and the results are as follows:\n", numofTests); for (i = 1; i <= numofTests; i++) { int currentResult = testResult(); printf("test %d: %d\n", i, currentResult); // 顺便帮你加上统计正负结果的逻辑(如果不需要可以删掉) if (currentResult == 1) { positiveResult++; } else { negativeResult++; } } // 调用你声明的其他函数展示统计结果 float positiveRate = positivePercentage(positiveResult, numofTests); displayResults(positiveResult, negativeResult, positiveRate); return 0; } // 移除内部的srand,只负责生成单个随机0/1 int testResult() { return (int)rand() % 2; } // 实现你声明的百分比计算函数 float positivePercentage(int positive, int total) { if (total == 0) return 0.0; return (float)positive / total * 100; } // 实现结果展示函数 void displayResults(int positive, int negative, float rate) { printf("\nSummary:\n"); printf("Positive tests: %d\n", positive); printf("Negative tests: %d\n", negative); printf("Positive rate: %.2f%%\n", rate); }
关键修改点
- 把
srand(time(NULL))从testResult()中彻底移除,只在main()开头执行一次,确保随机序列是连续且唯一的。 - 移除了
main()中重复的srand()调用,避免重复初始化干扰随机序列。 - 额外补充了统计正负结果的逻辑,匹配你声明的
positivePercentage和displayResults函数(如果不需要可以直接删掉这部分)。
这样修改后,每次调用testResult()都会从已初始化的随机序列中取下一个值,每个测试结果就会不一样啦!
内容的提问来源于stack exchange,提问作者Ahmet Caner Karaca
相关产品推荐
相关产品推荐

