C primer plus 第六版 第九章 第十题 编程练习答案

版权声明:转载请注明来源~ https://blog.csdn.net/Lth_1571138383/article/details/80536276

Github 地址:这里这里φ(>ω<*)

/*
    本程序应 习题-10 建立。
  题目要求: 改写程序清单 9.8 中的 to_binary() 函数。 
              编写一个 to_base_n() 函数接受两个参数,且第二个参数在2-10的范围内;
   然后以第二个参数中指定的进制打印第一个参数的数值。
     例子在 书 Page 276 。
*/


#include<stdio.h>


void to_base_n(int a, int b);


int main(void)

// 保存输入值和指定的进制。
int one = 0;
int two = 0;


printf("Please input two numbers :");
scanf_s("%d %d", &one, &two);


// 不循环输入只是懒得写了 !!!!!算法最重要。。当然这肯定不是懒的理由。。。
to_base_n(one, two);


printf("\nBye !\n");


getchar();
getchar();


return 0;
}


void to_base_n(int a, int b)
{
int count = 0;        // 计算用。


     // 本题 point !! 


if (b == 8)
{
count = a % 8;


if (a >= 8)
{
to_base_n( a / 8,  b);
}
else
{
// 空语句。
;
}


printf("%d", count);


}

else
{
// 题目指定在 2 - 10 的 范围内。则为 2 进制和 8 进制。其他进制。。。则忽略不计。
// 这个抄书上的。


count = a % 2;


if (a >= 2)
{
to_base_n(a / 2, b);
}
else
{
// 空语句。
;
}


putchar(count == 0 ? '0' : '1');


}

// 之所以用 return ; 是因为如果 void 类函数用 return 0 的话这个编译器会报错。
return;
}

猜你喜欢

转载自blog.csdn.net/Lth_1571138383/article/details/80536276