【发布时间】:2019-04-26 08:26:56
【问题描述】:
#include <iostream>
using namespace std;
int main()
{
//Declare data types
int NumChild; //var
const int BaseFee = 150; //constant
//Welcome + Instructions for users
cout << "Welcome to IOU Secondary School" << endl <<endl<< "How many
children are attending the school this year? "<<endl;
//Nested IF-ELSE (error checking)
if (cin >> NumChild)/
{
//do not accept any non-integer values
if (cin.peek() == EOF|| cin.peek() == '\n' )
{
}
else
{
cout <<endl<< "Error: enter a whole number."<<endl<< "The total
amount below represents the initial number entered e.g. if 5.7 is entered, the fee will be calculated according to 5 children" << endl;//error message for float entry
cin.ignore(100, '\n'); //read and discard up to 100 characters from the input buffer, or until a newline is read
cin.clear();//resets any error flags in the cin stream
}
}
else
{
// Edit: You should probably also clear the steam
cin.ignore(100, '\n');//read and discard up to 100 characters from
the input buffer, or until a newline is read
cin.clear(); //resets any error flags in the cin stream
cout << "Error: Restart the program and enter a number";
}
//nested IF statement (Calculation of fees)
if(NumChild == 1) //1 child attending
{
cout<<endl<<"The total cost of your child's fees are $"<< BaseFee+50 <<
endl;
}
if(NumChild == 2) //2 children attending
{
cout<<endl<<"The total cost of your children's fees are $"<< (BaseFee*2)+85
<< endl;
}
if(NumChild == 3)//3 children attending
{
cout<<endl<<"The total cost of your children's fees are $"<< (BaseFee*3)+110
<< endl;
}
if(NumChild > 3) //More than children attending
{
cout<<endl<<"The total cost of your children's fees are $"<<
(BaseFee*NumChild)+150 << endl;
}
}
有人可以解释一下 cin.peek 语句是什么以及在上面的代码中它在做什么吗? EOF|| cin.peek() == '\n') 对此有何影响。
当我输入一个浮点值时,第一个 else 值激活,但结果仍然显示。如何调整代码以使总费用不显示?
【问题讨论】: