c - 从 char 中提取 char。例如 1 from 123

标签 c

在这个程序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;
        }
                }

最佳答案

charchar* 之间存在差异。后者是指向 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/

相关文章:

c++ - 如何在 C 或 C++ 中使用语句 block 定义函数?

python - python支持哪些模块来生成c代码?

c++ - 如何使用 Apache C 模块记录到文件

c - sizeof 运算符与可变长度数组一起作为函数参数

c - 如何在 StringCbCatN() 中表示文件扩展名

c - 指向函数赋值的指针,C

c - 为什么 fopen 文件夹失败?

c++ - 如何使用 ULARGE_INTEGER 进行算术运算

c - 使用 2D 矩阵的 MPI_Sendrecv 问题

c - 我无法让错误 "Variable uninitialized"消失