C语言输出浮点数的符号、整数部分和小数部分 编写程序,从键盘输入一个不等于0的浮点数,然后分别输出这个浮点数的符号、整数部分和小数部分。例如输入-123.456,输出应该是(按下列格式输出): Sign:- Integral part:123 Decimal fraction part:0.456000
// 方法一:用abs求绝对值和int取整和三目运算符
#include "stdio.h"
#include "math.h"
int main()
{
double a;
int b;
double c;
scanf("%lf",&a);
printf("sign:%c\n",a <0?'-': '+');
b=abs((int)a);
printf("integral part:%d\n",b);
c=a>0? a-b:fabs((a+b));
printf("decimal fraction part:%lf\n",c);
}
// 方法二:用abs求绝对值和int取整和if判断
#include "stdio.h"
#include "math.h"
int main()
{
double a;
scanf("%lf",&a);
if (a<0)
{
printf("sign:-\n");
printf("integral part:%d\n",abs(int(a)));
printf("decimal fraction part:%f",abs(a-int(a)));
}
else
{
printf("sign:+\n");
printf("integral part:%d\n",abs(int(a)));
printf("decimal fraction part:%f",abs(a-int(a)));
}
}
// 方法三:用int取整和if判断
#include <stdio.h>
int main()
{
double a;
scanf("%lf",&a);
if (a<0)
{
printf("sign:-\n");
printf("integral part:%d\n",int(a)*-1);
printf("decimal fraction part:%f",(a-int(a))*-1);
}
else
{
printf("sign:+\n");
printf("integral part:%d\n",int(a)*-1);
printf("decimal fraction part:%f",(a-int(a))*-1);
}
}
// 方法四:
#include <stdio.h>
int main()
{
double a;
int b;
scanf("%lf",&a);
b = a;
if (a<0)
{
printf("sign:-\n");
printf("integral part:%d\n",b*-1);
if (a-b==0)
{
printf("decimal fraction part:%f",(a-b));
}
else
{
printf("decimal fraction part:%f",(a-b)*-1);
}
}
else
{
printf("sign:+\n");
printf("integral part:%d\n",b);
printf("decimal fraction part:%f",(a-b));
}
}
|