我的代码为什么输入什么结果都输出零
#include
#include
#include
int main()
{
int n;//模拟次数
int k=1,count=0;
srand((unsigned)time(NULL));
double r;
int T1,T3,T2;
scanf("%d",&n);
while(k<=n)
{
r=rand()%2;
if(r>=0&&r<0.7)
T1=0;
else if(r>=0.7&&r<0.9)
T1=5;
else
T1=10;
r=rand()%2;
if(r>=0&&r<0.3)
T3=28;
else if(r>=0.3&&r<0.7)
T3=30;
else if(r>=0.7&&r<0.9)
T3=32;
else
T3=34;
T2=rand()%2;
if(T1+T2>T3)
count=count+1;
k=k+1;
}
printf("赶上火车的频率p为%lf",count/n*0.1);
}
if(T1+T2>T3) 这个条件应该永远不成立,导致没执行,count为0
T1+T2不可能大于T3的,根据代码,T3至少为28,T1最大为10,T2最大为1
主要是count和n都是整数,且count小于n,所以35行count/n * 0.1=0 * 0.1 = 0
两个整数相除是整除,会丢失小数部分,所以你要改为 :
printf("赶上火车的频率p为%lf",count * 0.1 / n);
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int n;//模拟次数
int k=1,count=0;
srand((unsigned)time(NULL));
int r;
int T1,T3,T2;
scanf("%d",&n);
while(k<=n)
{
r=rand()%10;
if(r>=0&&r<7)
T1=0;
else if(r>=7&&r<9)
T1=5;
else
T1=10;
r=rand()%10;
if(r>=0&&r<3)
T3=28;
else if(r>=3&&r<7)
T3=30;
else if(r>=7&&r<9)
T3=32;
else
T3=34;
//用二项分布近似正态分布
T2=0;
for(r=0;r<16;r++){
T2+=rand()%2;
}
T2+=22;
if(T1+T2>T3)
count=count+1;
k=k+1;
}
printf("赶上火车的频率p为%lf",(double)count/n);
}
这个缩进实在难看代码
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!