[英]Need help do-while loop program? (C++)
我正在嘗試創建一個程序,該程序將接受用戶輸入(標記)並將這些標記的平均值輸出到字母等級。 我相信我已經成功地使程序成功地計算了平均值,但是它不會輸出正確的字母等級?
有什么建議么? 編輯:也許這是計算中的某件事,因為我的輸出始終將百分比表示為“ F”級。
// Used iomanip to display averages for possible three digit or greater answers.
#include <iostream>
#include <iomanip>
using namespace std;
// Set up my program using only main()
int main()
{
//Created the variable 'mark' so the user input can be stored and tested in the do-while condition.
//Variable 'sum' and 'average' to calculate mark and then be tested against letter grades.
//'counter' used to keep track of number of terms being averaged.
double mark=0, sum=0, average=0;
int counter=-1;
// Do-while statement to test the loop. Gets input from user, and tests whether it is a a valid letter grade.
// Marks below 0 or above 100 will test true and loop back re-promting the user for another mark.
// If tested condition is false, then if statements then test the mark and output the letter grade.
cout << "Please enter marks to calculate average, and enter -1 to stop and find letter equivalence. " << endl;
do
{
if ( mark < 0 || mark > 100 )
{
cout << "Entered mark is invalid. Please try again, or enter -1 to stop and find letter equivalence. " << endl;
break;
}
sum = sum + mark;
counter++;
cin >> mark;
}
while ( mark != -1 );
average = sum / counter ;
//What happens when above statement is false...
if (mark >= 90)
{
cout << "The average of "<<setprecision(2)<<average<<"% is equivalent to a letter grade of A+ ";
}
else if (mark >=80)
{
cout << "The average of "<<setprecision(2)<<average<<"% is equivalent to a letter grade of A ";
}
else if (mark >=70)
{
cout << "The average of "<<setprecision(2)<<average<<"% is equivalent to a letter grade of B ";
}
else if (mark >=60)
{
cout << "The average of "<<setprecision(2)<<average<<"% is equivalent to a letter grade of C ";
}
else if (mark >=50)
{
cout << "The average of "<<setprecision(2)<<average<<"% is equivalent to a letter grade of D ";
}
else
{
cout << "The average of "<<setprecision(2)<<average<<"% is equivalent to a letter grade of F ";
}
return 0;
}
需要考慮的幾件事:
您的成績分配應考慮average
而不是marks
。 如果使用標記,則最后一個輸入的值-1
用於退出do while循環)將用於評分,這將始終導致F評分。
在do-while
循環之后,將endl
添加到所有cout
語句中。 輸出流可能已被緩沖,這可能導致cout語句未出現在監視器上。 endl
將刷新輸出流。
例如。
cout << "The average of "<<setprecision(2)<<average<<"% is equivalent to a letter grade of A+ " << endl;
仔細檢查您的if
語句。 我敢打賭,您總是會看到正確的平均值等於F。
在循環結束時, mark
始終為-1
。 因此,所有測試均失敗,您進入了else
子句,並輸出了F。解決方法是測試average
而不是mark
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.