只使用I/O的PringDigit函数,编写一个过程以输出任意实数(可保留位数,四舍五入法)


#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打印单个位数*/
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值