[英]Need help converting to do while loop
I am new to programming and I have an assignment to do in C++.我是编程新手,我在 C++ 中有一个任务要做。 I need to convert this to do while loop.我需要将其转换为执行 while 循环。 Can someone help me out?有人可以帮我吗? Thanks in advance.提前致谢。
#include <iostream>
using namespace std;
int main()
{
int num;
float input, sum=0, avg;
cout<<"Input the amount of numbers: ";
cin >> num;
for(int i = 1; i <= num; i++){
cout<<"Enter a number: ";
cin >> input;
sum += input;
}
avg = sum / num;
cout << "The average is = " << avg << endl;
return 0;
}
Really simple.真的很简单。 Just put the header statements of your old for
loop in the following places: before the new loop, in the while
condition of the new loop, and inside the new loop as the last line of code, respectively.只需将旧for
循环的 header 语句放在以下位置:新循环之前,新循环的while
条件中,以及新循环内作为代码的最后一行,分别。
Here is your old loop code:这是您的旧循环代码:
for(int i = 1; i <= num; i++){
cout<<"Enter a number: ";
cin >> input;
sum += input;
}
And here is the new code:这是新代码:
int i = 1;
do {
cout<<"Enter a number: ";
cin >> input;
sum += input;
i++;
} while (i <= num);
Don't submit the assignment until you understand what I did, or you'll only be cheating yourself:) Check out this page for more info on a do...while
loop.在您了解我所做的之前不要提交作业,否则您只会欺骗自己:) 查看 此页面以获取有关do...while
循环的更多信息。 And it sounds like you could use some understanding on for
loops as well, so check them out here .听起来您也可以对for
循环有所了解,因此请在此处查看。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.