一个简单的C ++计算器程序,用于计算加法,减法,乘法和加法......
#include <iostream>
#include <string>
using namespace std;
int main()
{
//input declarations as doubles for total and counter
double total = 0, counter =0;
//input declarations sign and Q as character
char sign, Q = 0;
//input declaration value as double
double value;
//A do..while will loop forever (or until we hit the break statement)
do
{
//The current value is 0.
cout << "Result :"<<" "<< total << '\n';
//Please enter an operation
cout << "Please enter an operation and number : ";
cin >> sign;
//If the operation is Q, the program will end.
if (sign != 'Q')
cin >> value;
cin.ignore();
// If the value input is <=0, you can't divide anything by zero.
if (value <= 0)
{
cout << "Unknown Operator " << sign <<'\n' ;
}
//Otherwise procede with the calulator program
else
{
//If the operation is equal to '+', then the total is added.
if (sign == '+')
{
total += value;
}
// If the operation is equal to '-', then the value is subtracted from the previous number input.
else
{
if (sign == '-')
{
total -= value;
}
// If the operation is equal to '*', then the value is multiplied to the previous number input.
else
{
if (sign == '*')
{
total *= value;
}
// If the operation is equal to '/', then the value is divided by the previous number input.
else
{
if ((sign == '/')&&(value != 0))
{
total /= value;
}
}
}
}
}
}
//While the operation is not equal to 'Q', the program will run.
while (sign != 'Q');
return 0;
}
上述程序的编码没有错误,但如果我按“Q”退出,它将不停显示最后一个结果。 。一遍又一遍。 。 。无论如何,任何人都知道如何在程序中添加平方根。 。
答案 0 :(得分:1)
将if (sign != 'Q') ...
替换为if (sign == 'Q') break;
答案 1 :(得分:0)
#include <math.h>
double result = sqrt (value);
答案 2 :(得分:0)
对于平方根,
#include <math>
double r=sqrt(e);
关于您的其他问题:请更好地缩进您的代码; - )
你确定你没有忘记在这一行之后放一个街区吗?
if (sign != 'Q')
最简单的方法,在步进模式下使用调试器,你就会理解!
答案 3 :(得分:0)
作为一个简单的练习,我重构了你的程序,使其更简单。我不保证它有效,但它应该为你提供一个很好的基础:
#include <iostream>
#include <string>
using namespace std;
int main()
{
//input declarations as doubles for total and counter
double total = 0, counter =0;
//input declarations sign and Q as character
char sign = 0;
//input declaration value as double
double value;
//A do..while will loop forever (or until we hit the break statement)
do
{
//The current value is 0.
cout << "Current result: " << total << '\n';
//Please enter an operation
cout << "Please enter an operation (or Q to quit) and number: ";
cin >> sign;
//If the operation is Q, the program will end.
if (sign == 'Q' || sign == 'q') {
cout << "See you!\n";
break;
}
// If the input cannot be transformed into a double
// abort loop and try again
if (!(cin >> value)) {
cerr << "Invalid value entered, try again\n";
continue;
}
switch(sign)
{
case '+': total += value; break;
case '-': total -= value; break;
case '*': total *= value; break;
case '/':
if (value == 0) {
cerr << "Divide by 0 prevented!\n";
} else {
total /= value; break;
}
default:
cerr << "Unknown sign: " << sign << "\n";
}
} while (true);
return 0;
}
要点:
char
和数字)double
的转换可能会失败,可能会输入0