只使用I/O的PrintDigit函数,编写一个过程以输出任意实数

问题的描述如题所示,具体的是《数据结构与算法分析-C语言描述》中的习题1.3

看了后面的答案,第一句是这样的

由于舍入误差, 一开始不明白这句话是什么意思,因为答案中是有RoundUp这个函数的。经过反复的揣摩,发现double在内存中的存储是这样的,以前一直没有发现

 看到木有,定义的是8.1可在内存中显示的是趋近于8.1的数

接下来会研究下为什么会这样,下面是我补全后的代码

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;

void PrintDigit(int n)
{
	cout<<n;
}

double RoundUp(double N, int DecPlaces)
{
	int i;
	double AmountToAdd=0.5;
	for(i=0;i<DecPlaces;i++)
		AmountToAdd/=10;
	return N+AmountToAdd;
}

int IntPart(double N)
{
	return (int)N;
}

double DecPart(double N)
{
	return N-(int)N;
}

void PrintFractionPart(double FractionPart, int DectPlaces)
{
	int i,Adigit;

	for (i = 0; i < DectPlaces; i++)
	{
		FractionPart*=10;
		Adigit=IntPart(FractionPart);
		PrintDigit(Adigit);
		FractionPart=DecPart(FractionPart);
	}
}

void PrintOut(unsigned int n)
{
	if(n>=10)
		PrintOut(n/10);
	PrintDigit(n%10);
}

void PrintReal(double N, int DecPlaces)
{
	int IntergerPart;
	double FractionPart;

	if(N<0)
	{
		putchar('-');
		N=-N;
	}
	N=RoundUp(N, DecPlaces);
	IntergerPart=IntPart(N); FractionPart=DecPart(N);
	PrintOut(IntergerPart);
	if(DecPlaces>0)
		putchar('.');
	PrintFractionPart(FractionPart, DecPlaces);
}
int main()
{
	PrintReal(-8.101,3);
	cout<<endl;
	return 0;
}

运行结果:


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值