我的rand()函数有问题 我想建立一个程序,当你掷骰子6000次时显示每个骰子的数量
我写了这段代码
#include <iostream>
using namespace std;
#include <iomanip>
using std::setw;
#include <cstdlib>
#include <ctime>
int main()
{
int face ;
int frequency1 =0;
int frequency2 =0;
int frequency3 =0;
int frequency4 =0;
int frequency5 =0;
int frequency6 =0;
for(int counter =1;counter <=6000;counter++){
face = 1+rand()%6;
switch(face){
case 1:
++frequency1;
break;
case 2:
++frequency1;
break;
case 3:
++frequency1;
break;
case 4:
++frequency1;
break;
case 5:
++frequency1;
break;
case 6:
++frequency1;
break;
default:
cout<<"program should never get here!!! ";
break;
}}
cout<<"the number of face 1 is : "<<frequency1<<endl;
cout<<"the number of face 2 is : "<<frequency2<<endl;
cout<<"the number of face 3 is : "<<frequency3<<endl;
cout<<"the number of face 4 is : "<<frequency4<<endl;
cout<<"the number of face 5 is : " <<frequency5<<endl;
cout<<"the number of face 6 is : " <<frequency6<<endl;
return 0;
}
每次运行此代码时,它都显示相同的内容
the number of face 1 is : 6000
the number of face 2 is : 0
the number of face 3 is : 0
the number of face 4 is : 0
the number of face 5 is : 0
the number of face 6 is : 0
答案 0 :(得分:0)
您只是不断添加frequency1
而不是其他情况。我试图向你解释,但你似乎仍然不明白。这是编辑过的代码:
#include <iostream>
using namespace std;
#include <iomanip>
using std::setw;
#include <cstdlib>
#include <ctime>
int main() {
int face;
int frequency1 = 0;
int frequency2 = 0;
int frequency3 = 0;
int frequency4 = 0;
int frequency5 = 0;
int frequency6 = 0;
for(int counter =1;counter <=6000;counter++){
face = 1+rand()%6;
switch(face){
case 1:
++frequency1;
break;
case 2:
++frequency2;
break;
case 3:
++frequency3;
break;
case 4:
++frequency4;
break;
case 5:
++frequency5;
break;
case 6:
++frequency6;
break;
default:
cout<<"program should never get here!!! ";
break;
}
}
cout<<"the number of face 1 is : "<<frequency1<<endl;
cout<<"the number of face 2 is : "<<frequency2<<endl;
cout<<"the number of face 3 is : "<<frequency3<<endl;
cout<<"the number of face 4 is : "<<frequency4<<endl;
cout<<"the number of face 5 is : "<<frequency5<<endl;
cout<<"the number of face 6 is : "<<frequency6<<endl;
return 0;
}
如您所见,您的原始代码在所有案例陈述中都++frequency1
(递增)。这个编辑过的代码应该可行我已经解释了这个。