为什么我得到字符的负整数等值

我接受数字用空格分隔。 然后,我遍历各个字符以获取其等效的整数,如下面的代码所示:

#include <stdio.h>
#include <string.h>

int main()
{
    setbuf(stdout, NULL);

    int numLength;
    printf("Enter number length: ");
    scanf("%d",&numLength);

    getchar();
    char str[2*numLength];
    printf("Enter number: ");
    fgets(str, 2*numLength, stdin);

    for(int i=0;i<2*numLength;i=i+2)
    {
        printf("%d ",('0'-*(str+i)));
    }

    return 0;
}

以下是示例输出:

Enter number length: 5
Enter number: 2 k 6 a 0
-2 -59 -6 -49 0 

我的疑问是为什么它会给出负的整数等值?

(You can run the code online here)

评论
菊花开
菊花开

'0' - '2' is -2 for the same reason that 0 - 2 is also -2: '2' is greater than '0' by 2, so the result of subtracting the greater from the lesser number is -2.

You want *(str+i) - '0' (or str[i] -'0') if you want the result to be positive.

点赞
评论