的錯誤開始於cin.getline(字符串,25, '\ n');或者它下面的行(strtod)。如果我使用cin,它可以工作,但我不能退出。如果輸入任何不是雙精度的東西,就會運行一個無限循環。需要幫忙。基本上,第一次迭代運行,不要求輸入,所以用戶得到錯誤的數學問題。第二次迭代工作正常。接下來也很好。如果我退出,使用q,我會退回到模式選擇器。選擇一種模式後,該錯誤會再次出現在第一次迭代中。接下來的迭代已經結束了。第一次while循環的第一次迭代總是無法輸入。 2+循環做工精細
int main()
{
char choice, name[25], string[25], op;
int operator_number, average, difference, first_operand, second_operand, input, answer, total_questions = 0, total_correct = 0;
double dfirst_operand, dsecond_operand, dinput, danswer, percentage;
bool rounding = false;
srand (time(NULL));
cout << "What's your name?\n";
cin.getline (name, 25, '\n');
cout << '\n' << "Hi, " << name << ".";
do {
do {
cout << "\nWhich math operations do you want to practice?\n 1. Addition\n 2. Subtraction\n 3. Multiplication\n 4. Division\n 5. Mixed\n 6. Difference of squares multiplication.\nChoose a number (q to quit).\n";
cin >> choice;
} while(choice < '1' || choice > '6' && choice!= 'q');
cout << "\n";
switch(choice) {
case '1':
while(string[0]!= 'q') {
dfirst_operand = rand() % 15 + 1;
dsecond_operand = rand() % 15 + 1;
danswer = dfirst_operand + dsecond_operand;
cout << dfirst_operand << " + " << dsecond_operand << " equals?\nEnter q to quit.\n";
cin.getline (string, 25, '\n');
dinput = strtod(string,NULL);
//cin >> dinput;
if(string[0]!='q') {
++total_questions;
if(dinput==danswer) {
++total_correct;
cout << "Correct. " << total_correct << " correct out of " << total_questions << ".";
} else {
cout << "Wrong. " << dfirst_operand << " + " << dsecond_operand << " equals " << danswer << ".\n" << total_correct << " correct out of " << total_questions << ".";
};
percentage = floor(10000 * (float) total_correct/total_questions)/100;
cout << ' ' << percentage << "%.\n\n";
}
}
break;
}
} while(choice!='q');
return 0;
}
強制性鏈接到C++ FAQ精簡版:http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.2 – indiv 2010-03-05 21:12:12