全部问题 > 当前问题

为什么运行结果不是生成的随机数的和,该如何修改?

#include<stdio.h>

#include<stdlib.h>

#include<time.h>

main()

{

int t,i,n,y;

time(&t);

srand(t);

while(1)

{

system("cls");

printf("请输入生成随机数的个数:");

scanf("%d",&n);

if(n==0)

break;

y=0;

for(i=1;i<=n;i++)

{

printf("%d\n",rand());

y=y+rand();

}

printf("y=%d\n",y);

system("pause");

}

}


m 2015-11-15 15:02:08

共 5 个回答

嘿嘿大人 2015-11-15 19:48:18

#include<stdio.h>


#include<stdlib.h>


#include<time.h>


main()


{


int t,i,n,y,s;


time(&t);


srand(t);


while(1)


{


system("cls");


printf("请输入生成随机数的个数:");


scanf("%d",&n);


if(n==0)


break;


y=0;


for(i=1;i<=n;i++)


{

s=rand();


printf("%d\n",s);


y=y+s;


}


printf("y=%d\n",y);


system("pause");


}


}

因为rand()是一个库函数,所以像你之前那样用的话是不行的,因为你用一次这个rand()的值就会变一次,自然就不会是显示出来的那些随机数的和了

m 2015-11-22 09:55:52

回复 嘿嘿大人:改过之后,不知道为什么还是不行。

嘿嘿大人 2015-11-22 10:54:48

回复 m:你截图给我看看,我这里是可以的

m 2015-11-22 11:01:26

2345截图20151122110035.png


m 2015-11-22 11:01:41

#include<stdio.h>

#include<stdlib.h>

#include<time.h>

main()

{

int t,i,n,y,s;

time(&t);

srand(t);

while(1)

{

system("cls");

printf("请输入生成随机数的个数:");

scanf("%d",&n);

if(n==0)

break;

y=0;

for(i=1;i<=n;i++)

{

s=rand();

printf("%d\n",rand());

y=y+s;

}

printf("y=%d\n",y);

system("pause");

}

}




问题来自: 随机数