私は、ランダム関数でサイコロをシミュレートするプログラムを書いています。 これは私のコードですが、無限ループを抱えています。 プログラムは、サイコロを何回転がしたいかをユーザに尋ねることになっています。 次に、forループを使って1から6までのサイコロを振って、 としました。選択肢が1から6の範囲外であれば、ユーザーは1から6までの間で選択することができます。それが無効な選択であると言われています。 私は無限ループがdo
あるこのC++によるシングルダイスロールシミュレーション
#include<iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
//i is the counter for the loop
int i = 0;
//store total count for landing number
int num1 =0;
int num2 =0;
int num3 =0;
int num4 =0;
int num5 =0;
int num6 =0;
int Num1 =0;
int Num2 =0;
int Num3 =0;
int Num4 =0;
int Num5 =0;
int Num6 =0;
int randNum;
int times;
//User selection
int selection;
/* initialize random seed: */
srand ((unsigned int)time(NULL));
/* generate random number: */
randNum = rand() % 6 + 1;
cout<<"How many times would you like to roll the dice? " << endl;
cin >> selection;
do{
for(i = 1; i <= selection; i++)
{
if(randNum==1)
{
num1++;
}
else if(randNum==2)
{
num2++;
}
else if(randNum==3)
{
num3++;
}
else if(randNum==4)
{
num4++;
}
else if(randNum==5)
{
num5++;
}
else if(randNum==6)
{
num6++;
}
}
Num1 = num1/times *100;
Num2 = num2/times *100;
Num3 = num3/times *100;
Num4 = num4/times *100;
Num5 = num5/times *100;
Num6 = num6/times *100;
cout <<"# Rolled \t # Times \t % Times" << endl;
cout <<"----- \t ------- \t -------" << endl;
cout <<" 1 \t " << num1 << "\t " << fixed << setprecision(2) << Num1 << "%\n";
cout <<" 2 \t " << num2 << "\t " << fixed << setprecision(2) << Num2 << "%\n";
cout <<" 3 \t " << num3 << "\t " << fixed << setprecision(2) << Num3 << "%\n";
cout <<" 4 \t " << num4 << "\t " << fixed << setprecision(2) << Num4 << "%\n";
cout <<" 5 \t " << num5 << "\t " << fixed << setprecision(2) << Num5 << "%\n";
cout <<" 6 \t " << num6 << "\t " << fixed << setprecision(2) << Num6 << "%\n";
}
while(i >= 1 || i <= 6);
{
cout << "This is an invalid number. \n"
<< "The number of rolls should be equal to or greater than 1.\n"
<< "Please enter again.\n";
}
}
はあなたが他のすべての作業と出力を行う前に、有効な入力をチェックしたいようです。カウントの配列を考えてみると、ずっと簡単なコードになります。 'times'はあなたがそれを使うときに初期化されず、整数の数学はあなたに不正確な値を与えます。 forループの中でサイコロを動かすこともできます。 –
そして、コードを実行するためにデバッガを使用したときに、コードが "無限ループ"を実行する理由は何ですか? –
こんにちは、私はこのコードに配列や関数を使用することはできません – codeeeeeNOT