gpt4 book ai didi

c - 关于随机数生成

转载 作者:行者123 更新时间:2023-11-30 18:44:55 25 4
gpt4 key购买 nike

我写了代码,但当我编译它时,它似乎是一个错误的总和。你能帮助我吗?

There are n students that take course and there are five sections for this course write a c program using a function with prototype int random assignment that randomly assigns each student one of the five section and print which students is assigned to which section at the end of the program you should report how many students are in each section. Your function will generate a random number between 1 and 5.

#include<stdio.h>
#include<stdlib.h>
int fun(void){
return 1 +rand()%5;
}
int main(){
int numstu,count,a,sum1,sum2,sum3,sum4,sum5;
printf("Enter the number of students:");
scanf("%d",&numstu);
for(count=1;count<=numstu;count++){
a=fun();
printf("Student number %d assigned to %d\n",count,a);
if (a==1)
sum1=sum1+1;
if (a==2)
sum2=sum2+1;
if (a==3)
sum3=sum3+1;
if (a==4)
sum4=sum4+1;
if (a==5)
sum5=sum5+1;
}
printf("The number of student in section 1 is %d",sum1);
printf("The number of student in section 2 is %d",sum2);
printf("The number of student in section 3 is %d",sum3);
printf("The number of student in section 4 is %d",sum4);
printf("The number of student in section 5 is %d",sum5);
return 0;
}

最佳答案

您没有初始化任何变量,也没有执行任何错误检查。

这样做:

int numstu = 0, count = 0, a = 0;
int sum1 = 0, sum2 = 0, sum3 = 0, sum4 = 0, sum5 = 0;

并检查scanf的结果。

(为了可读性而将声明分开)

关于c - 关于随机数生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56305687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com