【问题标题】:Why is my to_base_n Program not working?为什么我的 to_base_n 程序不起作用?
【发布时间】:2016-01-07 10:02:28
【问题描述】:

我需要编写一个 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 时,我得到以下输出:

出现的大数字甚至比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:对不起,我在文中忽略了这一点。但是,伪代码通常更紧凑,所以我想知道您为什么要发布它。没关系!

标签: c base


【解决方案1】:

以 4 为底的数字 82000 将是: 110001100 这正是你得到的。你的错误是:

  • 它们是反向打印的。

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

【讨论】:

  • 谢谢!我认为这与垃圾有关,但我打算这样做来解决它:for(i=0; i&lt;16, i++){ digits[i]=0}
【解决方案2】:

您忽略了使用伪代码提取的位数,因此您打印了数组中未初始化的元素。

for (i = 0, i < 15, i++)
    print digits[i]

它们以相反的顺序打印。建议改成这个

for (i = i - 1, i >= 0, i--)
    print digits[i]

在你的函数中作为 C 代码

for(i = i - 1; i >= 0; i--)
    printf("%d|",digits[i]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多