#include<stdio.h>
void PrintReal(double N, int DecPlaces); // 打印实数N,保留其后DecPlaces位
double RoundUp( double N, int DecPlaces ); // 实现四舍五入的函数
int IntPart(double N); // 得到N的整数部分
double DecPart(double N); // 得到N的小数部分
void PrintFractionPart(double FractionPart, int DecPlaces); // 打印小数部分
void PrintDigit (int N);
void PrintOut(int N);
int main(void)
{
double RealValue,XiaoshuWeishu ;
printf("输入想显示的任意实数 :\n");
scanf("%lf",&RealValue);
printf("输入想显示的实数小数位数 :\n");
scanf("%lf",&XiaoshuWeishu);
printf("四舍五入后这个实数为:\n");
PrintReal(RealValue, XiaoshuWeishu); //输出实数value及其小数点后3位并四舍五入
printf("\n");
return 0;
}
void PrintReal(double N, int DecPlaces)// 打印实数N,保留其后DecPlaces位
{
int IntegerPart;
double FractionPart;
if( N < 0 ) //将实数N处理成正实数,输出前加“-”号
{
putchar('-');
N = -N;
}
N = RoundUp(N, DecPlaces); // 对实数N按要求实现四舍五入
IntegerPart = IntPart( N ); // 得到N的整数部分
FractionPart = DecPart( N ); // 得到N的小数部分
PrintOut(IntegerPart); // 打印N的整数部分
if(DecPlaces > 0)
putchar('.'); // 打印小数点
PrintFractionPart(FractionPart, DecPlaces);
}
double RoundUp( double N, int DecPlaces ) // 画龙点睛部分:四舍五入处理
{
int i;
double AmountToAdd = 0.5;
// 请在此添加代码,完成四舍五入
/********** Begin *********/
for (int i = 0; i < DecPlaces; i++)
{
AmountToAdd /= 10;
}
/********** End **********/
return N + AmountToAdd;
}
int IntPart(double N) // 得到N的整数部分
{
return (int)N;
}
double DecPart(double N) // 得到N的小数部分
{
// 请在此添加代码,取得N的小数部分
/********** Begin *********/
return N - IntPart(N);
/********** End **********/
}
/*
打印小数部分
*/
void PrintFractionPart(double FractionPart, int DecPlaces) //如小数部分是0.123,保留3位小数
{
int i, Adigit;
for( i = 0; i < DecPlaces; i++ )
{
FractionPart *= 10; // 第一次循环:小数部分乘以10,0.123*10=1.23
Adigit = IntPart(FractionPart);// 第一次循环:取1.23的整数1
PrintDigit(Adigit); // 第一次循环:递归打印整数1
// 请在此添加代码,为参与下一次循环处理做好准备
/********** Begin *********/
FractionPart = DecPart(FractionPart);
/********** End **********///
}
}
void PrintDigit (int N)
{
printf("%d ",N);
}
void PrintOut(int N) //教材P10例子
{
if(N>=10) /*1*/
PrintOut (N/10); /*2分离整数N的高位*/
PrintDigit (N%10); /*3打印单个位数*/
}