我正在制作一个基于控制台的计算器应用程序。应用程序处理用户按键以执行其操作。积分输入工作正常;但是,我在为用户按下退格键擦除十进制数的情况下编写代码时遇到问题。
我为擦除小数位而编写的代码如下:
decimalcount--; // number of decimal places is subtracted by 1
lnum -= fmod (lnum, pow (10, -decimalcount + 1)); // subtraction
cout << setprecision (decimalcount) << lnum << endl; // display the code
但是,对于某些数字,例如 12.00400679,这些值被不正确地减去:
12.00400679
12.00400670
12.0040060
12.004000
12.00400
12.0040
12.000
11.90
11.0
10
该程序的完整源代码如下:
#include <iostream>
#include <iomanip>
#include <cmath>
#include <conio.h>
using namespace std;
int sgn (double x)
{
if (x < 0)
{
return -1;
}
return 1;
}
int main ()
{
cout.setf (ios::fixed);
double lnum = 0, expr = 0;
int decimalcount = 0;
char ch, op;
while (true)
{
ch = _getch ();
if (isdigit (ch))
{
if (! decimalcount)
{
if (sgn (lnum) == sgn (lnum * 10 + sgn (lnum) * (ch - 48)))
{
lnum = lnum * 10 + sgn(lnum) * (ch - 48);
cout << setprecision (0) << lnum << endl;
}
}
else
{
if (decimalcount < 9)
{
lnum += sgn (lnum) * (ch - 48) * pow (10, -decimalcount);
cout << setprecision (decimalcount) << lnum << endl;
decimalcount++;
}
}
}
else if (ch == '\b')
{
if (! decimalcount)
{
lnum -= fmod (lnum, 10);
lnum /= 10;
cout << setprecision (0) << lnum << endl;
}
// This is where I am having problems
else
{
decimalcount--;
lnum -= fmod (lnum, pow (10, -decimalcount + 1));
cout << setprecision (decimalcount) << lnum << endl;
}
}
else if (ch == '.')
{
if (! decimalcount)
{
decimalcount = 1;
cout << setprecision (decimalcount) << lnum << endl;
}
}
else if (ch == 'x')
{
return 0;
}
}
}
谁能告诉我我做错了什么?
提前致谢,