while (counter < total)
{
inFile >> grade;
sum += grade;
counter++;
}
上面是我的原始程序的 while 循环,下面是我尝试将其转换为 for 循环。
for (counter = 0; counter < total; counter++)
{
inFile >> grade;
cout << "The value read is " << grade << endl;
total = total + grade;
}
这是一个获取平均成绩的简单程序。这是整个程序:
#include <iostream>
#include <fstream>
using namespace std;
int average (int a, int b);
int main()
{
// Declare variable inFile
ifstream inFile;
// Declare variables
int grade, counter, total;
// Declare and initialize sum
int sum = 0;
// Open file
inFile.open("input9.txt");
// Check if the file was opened
if (!inFile)
{
cout << "Input file not found" << endl;
return 1;
}
// Prompt the user to enter the number of grades to process.
cout << "Please enter the number of grades to process: " << endl << endl;
cin >> total;
// Check if the value entered is outside the range (1…100).
if (total < 1 || total > 100)
{
cout << "This number is out of range!" << endl;
return 1;
}
// Set counter to 0.
counter = 0;
// While (counter is less than total)
// Get the value from the file and store it in grade.
// Accumulate its value in sum.
// Increment the counter.
while (counter < total)
{
inFile >> grade;
sum += grade;
counter++;
}
// Print message followed by the value returned by the function average (sum,total).
cout << "The average is: " << average(sum,total) << endl << endl;
inFile.close();
return 0;
}
int average(int a, int b)
{
return static_cast <int> (a) /(static_cast <int> (b));
}
我尝试将 while 循环转换为 for 循环,但在调试时出现无限循环。构建解决方案时没有错误。我不确定要添加哪些其他详细信息。
最佳答案
您正在增加 for
循环中 total
的值。因此,如果您一直输入正值,counter
永远不会达到 total
。
也许您打算在循环中使用 sum
而不是 total
。
for (counter = 0; counter < total; counter++)
{
inFile >> grade;
cout << "The value read is " << grade << endl;
sum = sum + grade;
}
关于c++ - 如何在 C++ 中将 while 循环转换为 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33795244/