You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求将C++计算平均值的for循环代码转换为do-while循环

Convert C++ For Loop to Do-While for Average Calculation

Hey there! No problem at all—let's convert that for loop to a do-while loop step by step. The core logic stays the same (collecting num numbers, summing them up, then calculating the average), we just rearrange the loop structure to fit the do-while pattern.

Here's the modified code using do-while:

#include <iostream>
using namespace std;

int main() {
    int num, i = 1; // Initialize counter i here instead of in the for loop
    float input, sum = 0, avg;

    cout << "Input the amount of numbers: ";
    cin >> num;

    do {
        cout << "Enter a number: ";
        cin >> input;
        sum += input;
        i++; // Increment counter after processing each number
    } while (i <= num); // Keep looping until we've processed all numbers

    avg = sum / num;
    cout << "The average is = " << avg << endl;
    return 0;
}

Key changes explained:

  • We moved the counter variable i out of the for loop and initialized it to 1 at the top, since do-while loops don’t let you declare variables inside their structure like for loops do.
  • The do block runs first (so we always get at least one input—this makes sense here assuming num is a positive integer; if you wanted to handle cases where someone enters num <= 0, you could add a quick check before the loop, but that’s optional for your assignment).
  • After processing each number, we increment i, then the while condition checks if we still need to collect more numbers (i.e., if i is still less than or equal to num).
  • All the other logic (summing values, calculating the average, and printing the result) stays exactly the same as your original code.

If you test this with the same input as your original program, you’ll get the exact same result. Let me know if you need any clarification on any part!

内容的提问来源于stack exchange,提问作者Audrey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:06:24