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

标签 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 循环,但在调试时出现无限循环。构建解决方案时没有错误。我不确定要添加哪些其他详细信息。

最佳答案

您正在增加 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/

相关文章:

c++ - 学习OpenGL需要什么?

bash - 使用 `for` 循环逐行读取

java - 猜谜游戏中的随机数

php - while 循环在从表中选择多列时不起作用

c++ - 如何使用 CMake 在 Windows 上将 C++ 应用程序入口点设置为 main()?

c++ - 使用 boost::bind 和 boost::lambda::new_ptr 返回一个 shared_ptr 构造函数

c++ - 从C++中的Content-Disposition header 正确提取文件名的更快方法

algorithm - Big-O for 循环运行时分析

java - 在Python中, "args = [temp[n] for n in array(index)]"是否在检查temp[n]?

c# 类、结构或接口(interface)成员声明中的无效标记 'while'(循环不起作用)