C PRIMER PLUS第九章第10题进制转换

本文介绍如何编写一个名为to_base_n的函数,接收2到10范围内的基数和整数,将整数转换为目标基数的表示形式。通过实例演示和输入验证,展示了函数的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

编写一个to_base_n()函数接受两个在2-10范围内的参数,然后以第1个参数中制定的进制打印第2个参数的数值。例如,to_base_n(129,8)显示的结果为201,也就是129的八进制数。在一个完整的程序中测试该函数。

以下为代码:

#include <stdio.h>

void to_base_n(int n, int x);
int main(void)
{
	int n, x;
	
	printf("Enter a number and the base for the form of prints.\n");
	printf("Now enter the number in the demical system: ");
	scanf("%d", &x);
	printf("Enter the base of it(2-10): ");
	scanf("%d", &n);
	while(n < 2 && n > 10)
	{
		printf("Enter the base(2-10): ");
		scanf("%d", &n);
	}
	to_base_n(n, x); 
	return 0;
 } 
 
 void to_base_n(int n, int x)
 {
 	if(x < 0)
 	{
 		x *= -1;
 		printf("-");
	 }
 	if(x > 0)
 	{
 		to_base_n(n, x / n);
 		printf("%d", x % n);
	 }
 	return;
 }
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值