在这个程序convert.c中,我试图将任意基数的给定数字转换为基数10。该命令的给出是因为convert .todecimal应该做到这一点。下面的代码当然有错误,但我不确定如何使其工作。例如,argv[3] 中的数字是以 9 为基数的 123。该方程应该如下所示:(1 x 9^2) + (2 x 9^1) + (3 x 9^0) = ( 102)10.其中变量是 (n x argv[3]^i) + (n+1 * argv[3]^i-1)....当 123 本身是一个字符时,如何获得 123 的字符?如有任何帮助,我们将不胜感激。
#include<stdio.h>
#include<math.h>
int todecimal();
main(int argc, char *argv[])
{
int s = 0;
int i = 0;
int n = 1;
if (argc < 4) {
printf("Usage: convert <basefrom> <baseto> <number>\n");
}
printf("to decimal prints %d" todecimal());
}
int todecimal() {
if (argv[3] > 0) {
if ((getchar(argv[3]) != NULL)) {
i = i + 1;
}
while (i >= 0) {
s = s + (n * (pow(argv[3],i)));
n = n + 1;
i = i - 1;
}
return s;
}
}
最佳答案
char
和 char*
之间存在差异。后者是指向 char 的指针,也用作字符串(字符序列)。因此,只要您可以拥有多个 char
,您就可以使用指针(指向第一个字符) - 这是您的 argv[3]
。
因此,要从一系列 char
中获取一个 char
,请使用方括号:
argv[3] - is the whole string, let's pretend it's "192" to reduce confusion
argv[3][0] - is the first char, '1'
argv[3][1] - is the second char, '9'
argv[3][2] - is the third char, '2'
就您而言,您需要argv[3][i]
。但您也必须修复其他错误(正如其他人指出的那样,有很多错误)。
关于c - 从 char 中提取 char。例如 1 from 123,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28530768/