我一直在嘗試撰寫一個程式,該程式從用戶那里獲取分數,然后通過輸入驗證計算平均值。我唯一不知道的是如何判斷輸入的分數大于 80 的數量。此外,我必須在不使用陣列的情況下執行此操作。
這是我目前擁有但不作業的內容,并從 5 而不是 1 開始計數器,然后在輸入大于 80 的分數時將其遞增。
int main()
{
int score, sum=0, greater=0;
for(int i=1; i<=5; i )
{
cout<<"Enter the score: "; //take user input for scores
cin>>score;
if(score>80)
{
for (int i=1; i<=5; i ){
greater= greater 1;
}
cout<<"There are "<<greater<<" number more than 80";
}
while (! (score >=0 && score <= 100 )) //input validation
{
cout << "Invalid Input. Enter the score between the range 0 - 100" << endl;
cout << "Enter the score: ";
cin >> score;
}
sum = sum score;
}
float avg;
avg = sum/5.0; //calculating the average
cout<<"Average of scores: "<<avg<<endl;
有人可以幫我嗎?將不勝感激。謝謝!
我嘗試了上面列出的代碼并嘗試對其進行調整,但它仍然顯示計數為 5 的倍數。
uj5u.com熱心網友回復:
您混淆了代碼中的陳述句序列。
強烈提示:如果您寫評論,那么您將避免此類問題。
請參閱下面的更正代碼
#include <iostream>
#include <limits>
using namespace std;
int main() {
int score, sum = 0, greater = 0;
// Get 5 values from user
for (int i = 0; i < 5; i )
{
// We ant to validate the input and use the below to indicate the result
bool validValue = false;
// Now read values, until we get a valid one
do {
// We initially assume that the value is good
validValue = true;
// Get user input
cout << "\n\nEnter a score. Valid values are 0...100: "; //take user input for scores
cin >> score;
// Check, if the user entered some ivalid data like "abc"
if (!cin) {
validValue = false;
// Reset error flag from cin
cin.clear();
// Discard the rest of invalid characters taht are still in the input stream
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip bad input
}
// Check for valid range
else if (score < 0 or score > 100)
// Problem. Indicate
validValue = false;
if (not validValue)
std::cout << "\nError: Invalid value given. Please try again\n";
// contiinue the loo, until we get a valid value
} while (not validValue);
// Ok, now we have a valid value
// Check, if the score meets our condition
if (score > 80)
// Then counte up
greater = greater 1;
// Calculate the overall sum, so that we can evaluate the average later
sum = sum score;
}
// So, now we have read 5 values
// Calculate the avarage of all scores
double avg;
avg = sum / 5.0; //calculating the average
// And now show the result on the screen
cout << "There are " << greater << " number more than 80\n";
cout << "Average of scores: " << avg << '\n';
}
uj5u.com熱心網友回復:
據我了解,不需要 if 陳述句中存在的 thenfor 回圈。只需保留更大變數的增量邏輯和內部 for 回圈。還要在外部 for 回圈之后移動 if 陳述句內的 print atatement。這會給你用戶輸入的分數大于 80
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/528600.html
標籤:C 循环嵌套循环
