问题描述
我想分开实数的整数部分和小数部分。
即使输入了56.345 int部分将显示为56,frctional部分显示为345.以下是我尝试的代码:
Hi,
I want to seperate the integral part and fractional part of a real number.
That is if 56.345 is entered the int part will be shown as 56 and frctional part as 345. Here is the code I tried:
#include<iostream.h>
#include<conio.h>
int main()
{
float x;
int a[15],b[15];
clrscr();
cout<<"\nEnter the number:";
cin>>x;
int y=x;
float z=(x-y);
cout<<"\nInteger part :"<<y;
cout<<"\nFractional part :"<<z;
getch();
return 0;
}
输出结果如下......
The output is as follows...
case 1:
Enter the number:24.41
Integer part :24
Fractional part :0.41
case 2:
Enter the number:56.345
Integer part :56
Fractional part :0.345001
在第二种情况下,我无法获得正确的答案。我可以通过使用char数组解决这个问题,但我不想使用那种方法。
(编辑使文本看起来像英文而不是阿里-G湿梦想)。
In the second case I can't obtain the correct answer. I can solve this by using a char array but I dont want to use that method.
(Edited to make the text look like English and not an Ali-G wet dream).
推荐答案
double x = 0.0;
std::cin >> x;
int y = int( x * 100000 );
std::cout << "Integral part: " << y / 100000 << std::endl
<< "Fractional part: " << y % 100000 << "/10000" << std::endl;
这不适用于不适合整数的大数字。例如,乘以10,000会使整数中大约一半的位用于保持小数部分,从而使您的范围更大。最终你必须弄清楚你可以接受的范围和不准确度。并且可以使用它。
干杯,
Ash
This won't work with big numbers that won't fit in an integer. Multiplying by 10,000 for example makes about half the bits in the integer be used for holding the fractional part so you loose even more range. Ultimately you've got to work out what range and inaccuracy are acceptable to you and go with it.
Cheers,
Ash
#include <iostream>
#include <iomanip>
int main()
{
float f=1;
while (f)
{
std::cin >> f;
int i = (int)f;
std::cout << i << '\t' << std::setprecision(3) << f - i << std::endl;
}
return 0;
}
欢呼,
AR
cheers,
AR
这篇关于如何分离整数部分和小数部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!