c - 为什么我的 to_base_n 程序不工作?

标签 c radix

我需要编写一个 C 程序,它将从用户输入中读取一个数字(以 10 为基数)并将其输出为任何以 2 为幂的基数。计算必须在一个函数中执行,to_base_n ,它采用参数 numbase 并打印相应基数中的数字。作为验证检查,该程序还使用 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 时,我得到以下输出:

Output

出现的大数字甚至比 num 本身还大,所以我认为模数不能正确地进入数组(因为∀{x,n}; x mod n < x)。我似乎找不到它有什么问题。完整代码如下。

#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]);
}

谁能帮忙解释一下这是怎么回事?

最佳答案

基数 4 中的数字 82000 将是: 110001100 这正是你得到的。你的错误是:

  • 它们是反向打印的。

  • 你打印的数字比你应该打印的多,所以你打印了垃圾。

关于c - 为什么我的 to_base_n 程序不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34652245/

相关文章:

c - C 中的 Flex Bison 段错误

c - __libc_lock_lock 是段错误

c - 需要 __alignof__ 的调试符号

c - 哪里可以找到timespec_get的源代码?

c# - 数组有字符串值,我想要一个整数

c# - 自定义异常和基本构造函数

c - 在数字基数之间转换的递归函数在某些数字处失败

java - C代码如何不可重用而Java如何使用继承来拥有可重用代码?

css - Web 标记,背景颜色设置为基础

php - 如何从 WordPress 获取所有基本(父或根)类别