我试图在一个简单的程序中实现do..while循环。在程序中,我要求工资金额,然后计算工资单的总和并输出总和和有效条目的数量。这太简单了,所以我决定添加一些错误检查。
#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
const int SENTINEL = -1;
int main(){
int payroll, payroll_sum, counter = 0;
do{
cout << "Enter a payroll amount (-1 to end): ";
cin >> payroll;
if((payroll < SENTINEL)){
cout << "\nError!\nPlease enter a correct value.\n" << endl;
int main(payroll);
}
else{
payroll_sum += payroll;
counter += 1;
cout << "\n";
}
if(payroll == SENTINEL){
payroll_sum += 1;
counter -= 1;
}
}while(payroll != SENTINEL);
cout << "\n\nTotal payroll amount is: " << payroll_sum;
cout << "\nTotal number of entries is: " << counter;
return 0;
}
代码有效,但是我不得不从计数器中扣除一个并在总和中加一个,因为我不知道如何让程序忽略SENTINEL输入。而且,我确信有更好的方法来进行错误处理。提前谢谢。
答案 0 :(得分:0)
使用
continue;
而不是
int main(payroll);
此外,使用
初始化payroll_sum
payroll_sum=0
循环之前。另外,删除
if(payroll == SENTINEL){
payroll_sum += 1;
counter -= 1;
}
并将最后两个cout
更改为
cout << "\n\nTotal payroll amount is: " << payroll_sum+1;
cout << "\nTotal number of entries is: " << counter-1;
答案 1 :(得分:0)
这就是我写它的方式,因为它相当清洁。我注意到一些事情你可能想要注意:
continue
和break
以及何时使用do-while
或while
循环。快乐的编码!
const int SENTINEL = -1;
int main() {
int payroll_sum = 0;
int payroll = 0;
int counter = 0;
while (payroll != SENTINEL) {
cout << "Enter a payroll amount (-1 to end): ";
cin >> payroll;
if(payroll == SENTINEL) break;
if((payroll < SENTINEL)){
cout << "\nError!\nPlease enter a correct value.\n" << endl;
continue;
}
else {
payroll_sum += payroll;
counter++;
}
}
cout << "\n\nTotal payroll amount is: " << payroll_sum;
cout << "\nTotal number of entries is: " << counter;
return 0;
}
答案 2 :(得分:0)
似乎是一个关于条件逻辑的简单问题。有很多不同的方法来构建你的if条件,但有一种方法比你当前的代码更有效:
while(true)
{
cout << "Enter a payroll amount (-1 to end): ";
cin >> payroll;
if(payroll == SENTINEL)
break;
if((payroll < SENTINEL))
{
cout << "\nError!\nPlease enter a correct value.\n" << endl;
int main(payroll);
}
else
{
payroll_sum += payroll;
counter += 1;
cout << "\n";
}
}
如果你不喜欢使用while(true),我可以提供另一个例子。干杯