【发布时间】:2018-04-15 03:26:54
【问题描述】:
所以,需要做的是:输入一个实数,打印小数点后前4位的和。例如:我输入 5.1010。我到了需要将 0.1010 乘以 10000 才能变成整数的地步,但我得到的结果是 1009 而不是 1010,之后一切都崩溃了。 如果有人能向我解释为什么会发生这种情况,我将永远感激不尽。
#include<iostream>
using namespace std;
int main()
{
double n;
cout<<"Enter a positive real number: ";
do
{
cin>>n;
if(n<=0) cout<<"The number must be positive, enter again: ";
}while(n<=0);
//storing the fractional part in a var
int y=n;
double fr=n-y;
//turning the fractional part into an integer
int fr_int=fr*10000;
cout<<fr_int<<endl;
//storing each of the digits in a var
int a=fr_int/1000;
int b=fr_int/100%10;
int c=fr_int/10%10;
int d=fr_int%10;
cout<<"The sum of the first 4 digits is: " << a+b+c+d;
return 0;
}
【问题讨论】:
标签: c++