임의의 기능을 가진 주사위 굴림을 시뮬레이트하는 프로그램을 작성 중입니다. 이것은 내 코드이지만 무한 루프가 발생했습니다. 프로그램은 사용자에게 주사위를 굴릴 횟수를 묻는 메시지를 표시합니다. 그런 다음 for 루프를 사용하여 주사위를 1에서 6으로 굴립니다. 을 모두 넣었습니다. 선택 사항이 1에서 6까지 밖에없는 경우 사용자가 1에서 6 사이 만 선택할 수 있도록하려면 그것이 잘못된 선택이라고 말하기로되어 있습니다. C++로 단일 주사위 굴림 시뮬레이션
난 당신이 뭘하려고했는지 모르겠어요 ...while
,하지만 당신은 것입니다 - I이
#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