简体   繁体   English

使用atoi将字符串索引转换为数组索引

[英]Using atoi to convert string index to array index

I'm doing a code which calculates the sum of the digits of a factorial, my solution was to convert the number to a string then put that string on an array. 我正在做一个计算阶乘数字之和的代码,我的解决方案是将数字转换为字符串然后将该字符串放在数组上。

I tried using atoi to convert a string index to the array index, but it doesn't work, giving me the error "passing argument 1 of 'atoi' makes pointer from integer without a cast" 我尝试使用atoi将字符串索引转换为数组索引,但它不起作用,给我错误“传递'atoi'的参数1使得指针来自整数而没有强制转换”

#include <string.h>
#include <stdlib.h>
int fat(int x)
{
    if (x == 0 || x == 1)
    {
        return 1;
    }
    else
    {
        return x * fat(x-1);
    }
}

int main()
{
    int n, i, f=0, arr[30];
    char str[30];
    printf("Type the value of N: ");
    scanf("%d",&n);
    for (i=1;i<=n;i++)
    {
        f = fat(i);
    }
    printf("%d \n", f);
    sprintf(str, "%d", f);
    n=0;
    for (i=0;i<strlen(str);i++)
    {
        arr[i]=atoi(str[i]);
        n=n+arr[i];
    }
    printf("%d", n);
}

If you just want to convert a single digit character to a number, you don't need to use atoi() . 如果您只想将单个数字字符转换为数字,则不需要使用atoi() Use str[i] - '0' . 使用str[i] - '0'

        arr[i] = str[i] - '0';

There also doesn't seem to be much point to the array. 阵列似乎也没有多大意义。 You can just do: 你可以这样做:

        n += str[i] - '0';

without saving all the numbers in an array that you never use again. 不保存您再也不会使用的数组中的所有数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM