用 C 语言编写一个程序,该程序将采用基数和 n 位数字,并输出由这些数字表示的十进制数

Write a program in C that will take a base and n digits and will output a decimal number represented by those digits

我必须用 C 编写一个程序,它将从用户那里获取一个基数 b(假设 b 介于 2 和 10 之间),一个自然数 n,然后是 n 表示基数 b 中某个数字 m 的数字的数字。该程序应打印出输入的十进制数 m。例如,如果您输入 b=5n=4,然后输入数字 3421,程序应输出 486 因为 m=3*5^3+4*5^2+2*5^1+1*5^0=486

注意:您可以假设数字将是 0b-1 之间的数字。

这就是我所做的:

#include<stdio.h>
#include<math.h>

int main(void) {
    int x,n,b,k=0,num=0,i,j;
    scanf("%d", &b);
    scanf("%d", &n);
    for(i=1; i<=n; i++) {
        scanf("%d", &x);
        for(j=1; j<b; j++){
            if(j>k){
                num=num+x*(pow(b,n-j));
                k=j;
                break;
                }
        }
    }

    printf("m=%d", num);

return 0;
}

你能告诉我为什么这对上面例子中给出的数字不起作用吗?它输出 485 而不是 486,而如果我以 b=7, n=3 为例,然后是数字 5, 61,我会得到正确的解决方案 m=288.

好的,给定一个二进制数,我们可以很容易地输出一个十进制数。只是 printf("%d%\n", x);

下一个工作是将给定数字和基数的数字转换为二进制(机器表示)数字。

  int basetointeger(const char *digits, int b)
  {
      assert(b >= 2 && b <= 10);
      // code here

      return answer;
  }

现在把它全部连接到 main

int main(void)
{
     int x;
     int base;
     char digits[64];  // give more digits than we need, we're not worrying about oveflow yet
     /* enter base *?
     code here
     /* enter digits */
     code here
     x = basetointger(digits, base);
     printf("Number in decimal is %d\n, x);
}

我建议检查 scanf() 的 return 值,这样的想法是正确的:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int
main(int argc, char *argv[]) {
    int base, n, i, x, sum = 0, power;

    printf("Enter base: ");
    if (scanf("%d", &base) != 1) {
        printf("Invalid base.\n");
        exit(EXIT_FAILURE);
    }

    printf("Enter n: ");
    if (scanf("%d", &n) != 1) {
        printf("Invalid n.\n");
        exit(EXIT_FAILURE);
    }

    power = n-1;

    printf("Enter numbers: ");
    for (i = 0; i < n; i++) {
        if (scanf("%d", &x) != 1) {
            printf("Invalid value.\n");
            exit(EXIT_FAILURE);
        }
        sum += x * pow(base, power);
        power--;
    }

    printf("Sum = %d\n", sum);

    return 0;
}

输入:

Enter base: 5
Enter n: 4
Enter numbers: 3 4 2 1

输出:

Sum = 486

您需要对您的逻辑做一些小改动。

#include <stdio.h>
#include <math.h>

int main(void) {
    int x, n, b,  num = 0, i;
    scanf("%d", &b);
    scanf("%d", &n);
    for (i = 1; i <= n; i++) {
        scanf("%d", &x);
        num += x * pow(b, n - i);
    }
    printf("m=%d", num);
    return 0;
}

测试

gcc -Wall main.c -lm
$ ./a.out
5
4
3
4
2
1
m=486  

测试 2

 ./a.out
7
3
5
6
1
m=288