《数据结构与算法分析–C语言描述 2ed》习题 1.3 只使用处理I/o的PrintDigit函数,编写一个过程以输出任意实数(可以是负的)

在这里插入图片描述

题目

1.3 只使用处理I/o的PrintDigit函数,编写一个过程以输出任意实数(可以是负的)

官方答案

Because of round-off errors, it is customary to specify the number of decimal places that
should be included in the output and round up accordingly. Otherwise, numbers come out
looking strange. We assume error checks have already been performed; the routine
SeparateO is left to the reader. Code is shown in Fig. 1.1

code – Text 1.3

#define _crt_secure_no_warnings
#include<iostream>
using namespace std;
//------------------------------------------ - example1.3-------------------------------- -//
//书本1.3章节的例子

//输出一位数
void PrintDigit(unsigned int temp)
{
	cout << temp;
}
//输出数字
void PrintOut(unsigned int n)
{
	if (n >= 10)
	{
		PrintOut(n / 10);
	}
	PrintDigit(n % 10);
}
//------------------------------------------ - text1.3-------------------------------- -//
//习题  1.3 只使用处理I/O的PrintDigit函数,编写一个过程以输出任意实数(可以是负的)

//浮点数的舍入问题--不是很懂,需要结合内存和计算机组成原理来分析!!!!!
double RoundUp(double n, int DecPlaces)
{
	int i;
	double AmountToAdd = 0.5;
	for (int i = 0; i < DecPlaces; i++)
	{
		AmountToAdd /= 10;
	}
	return (n + AmountToAdd);
}

//C库函数 modf	https://www.runoob.com/cprogramming/c-function-modf.html 
//取出整数部分
int IntPart(double FractionPart)
{
	double  integetPart = 0;
	modf(FractionPart, &integetPart);
	return integetPart;

	//return ((int)FractionPart);
}
//取出小数部分
double DecPart(double FractionPart)
{
	double integetPart=0;
	FractionPart = modf(FractionPart, &integetPart);
	return FractionPart;

	//return (FractionPart - ((int)FractionPart));

}
//打印小数部分
//参数是:小数、有几位小数
void PrintFractionPart(double FractionPart, int DecPlaces)
{
	int i;
	int Adigit;
	for (int i = 0; i < DecPlaces; i++)			//依次打印小数点后的各位数字
	{
		FractionPart *= 10;						//小数部分乘10
		Adigit = IntPart(FractionPart);			//取出这一位整数
		PrintDigit(Adigit);						//打印
		FractionPart = DecPart(FractionPart);	//取出小数部分,重新赋值
	}
}

void PrintReal(double N, int DecPlaces)
{
	int IntegerPart;							//整数部分
	double FractionPart;						//小数部分
	if (N < 0)
	{
		putchar('-');
		N = -N;
	}
	N = RoundUp(N, DecPlaces);
	IntegerPart = IntPart(N);					//取出整数部分
	FractionPart = DecPart(N);					//取出小数部分
	PrintOut(IntegerPart);						//先 打印整数部分 //using routine in text
	if (DecPlaces > 0)							//若是负数,再打印 . 
	{
		putchar('.');
	}
	PrintFractionPart(FractionPart, DecPlaces);	//最后打印小数部分
}
#if 1
int main()
{
	PrintOut(76234);
	cout << endl;
	PrintReal(9.1,1);
	cout << endl;
	system("pause");
	return 0;
}
#endif

参考博客
博客1
博客2
舍入问题

一个有意思的想法

#include <stdio.h>

int main(void) {
    char temp;

    temp = getchar();
    while (temp >= '0'&&temp <= '9') {
        printf("%c ", temp);
        temp = getchar();
    }
    printf("\n");

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值