题目1.3只使用处理I/O的PrintDigit函数,编写一个过程以输出任意实数(可以是负的)。
原书对PrintDigit的定义包含在一个作为范例的源代码中,这个源代码通过递归实现只用PrintDigit函数(一次输出一个数字)输出一串数字
#include <stdio.h>
#include <stdlib.h>
#define PrintDigit( Ch ) ( putchar( ( Ch ) + '0' ) )
/* START: fig1_4.txt */
void
PrintOut( unsigned int N ) /* Print nonnegative N */
{
if( N >= 10 )
PrintOut( N / 10 );
PrintDigit( N % 10 );
}
/* END */
main( )
{
PrintOut( 1369 );
putchar( '\n' );
return 0;
}
而题目1.3的答案源代码如下
<pre name="code" class="cpp"><span style="font-family:Arial, Helvetica, sans-serif;">//将要输出的函数四舍五入,decimal(小数),变量DecPlaces指小数部分</span>
<span style="font-family: Arial, Helvetica, sans-serif;">double RoundUp( double N, int DecPlaces ) </span>
{
int i;
double AmountToAdd = 0.5; //举例N=2.567,DecPlaces=2,则N+AmountToAdd=2.572,同样情况下N=2.564时,N+AmountToAdd=2.569。这样保留两位小数时实现四舍五入
for( i = 0; i < DecPlaces; i++ )
AmountToAdd /= 10;
return N + AmountToAdd;
}
void PrintFractionPart( double FractionPart, int DecPlaces )
{
int i, Adigit;
for( 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 );
}