【发布时间】:2016-01-07 10:02:28
【问题描述】:
我需要编写一个 C 程序,该程序将从用户输入中读取一个数字(以 10 为基数)并以 2 的幂的任何基数输出。计算必须在一个函数中执行,to_base_n,它采用参数num 和base 并在各自的基数中打印数字。作为验证检查,该程序还使用 isPowerofTwo 函数检查基数是否为 2 的幂。
执行转换的方式是通过长除法执行以下伪代码中的逻辑:
void to_base_n(int x, int n){
int r, i = 0
int digits[16]
while (x ≠ 0){
r = x mod n
x = x / n
digits[i] = r
i++
}
for (i = 0, i < 15, i++)
print digits[i]
}
我认为这在算术上是合理的。但是,例如,当我尝试将 82000 转换为基数 4 时,我得到以下输出:
出现的大数字甚至比num 本身还要大,所以我认为模数不能正确进入数组(因为∀{x,n}; x mod n
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
bool isPowerofTwo(int);
void to_base_n(int, int);
int main(){
//Variables
int num, base;
//Prompt
printf("Please enter a number in base 10: ");
scanf("%d", &num);
printf("Please enter a base (2^n) to convert it to: ");
scanf("%d", &base);
//Precaution
while(!isPowerofTwo(base)){
printf("That number is not a power of 2. Please try again: ");;
scanf("%d", &base);
}
if(isPowerofTwo(base)){
//Output
printf("The number %d (base 10) is equivalent to ", num);
to_base_n(num, base);
printf(" (base %d).", base);
}
//Return Statement
return 0;
}
//Checks if Base is a Power of Two
bool isPowerofTwo(int base){
while((base % 2 == 0) && base > 1){
base = base / 2;
if(base == 1){
return true;
break;
}
}
return false;
}
//to_base_n
void to_base_n(int x, int n){
int r, i = 0;
int digits[16];
while(x != 0){
r = x % n;
x = x / n;
digits[i] = r;
i++;
}
for(i = 0; i < 15; i++)
printf("%d|",digits[i]);
}
谁能帮忙解释一下它有什么问题?
【问题讨论】:
-
检查您写入的数组的边界是一个好习惯 (i
-
这甚至不能编译。
-
@Olaf 你需要一个伪代码编译器。
-
@Olaf C 程序本身应该可以正常工作,除非您尝试编译伪代码。
-
@LukeCollins:对不起,我在文中忽略了这一点。但是,伪代码通常更紧凑,所以我想知道您为什么要发布它。没关系!