题目
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
一个有意思的想法
#include <stdio.h>
int main(void) {
char temp;
temp = getchar();
while (temp >= '0'&&temp <= '9') {
printf("%c ", temp);
temp = getchar();
}
printf("\n");
return 0;
}