如何在C ++中将while循环转换为for循环?

时间:2015-11-19 04:23:40

标签: c++ for-loop while-loop

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循环,但是当我调试时,我得到一个无限循环。构建解决方案时没有错误。我不确定要添加的其他细节。

2 个答案:

答案 0 :(得分:5)

您正在total循环中增加for的值。因此,如果您继续输入正值,则counter永远不会达到total

也许您打算在循环中使用sum而不是total

for (counter = 0; counter < total; counter++)
{
    inFile >> grade;        
    cout << "The value read is " << grade << endl;
    sum = sum + grade;  
}

答案 1 :(得分:1)

您正在使用错误的变量名称,{for循环中total的值正在增加,因此它变为无限循环,使用不同的变量名来存储和以及for-loop终止条件。