我将以下输入作为字符串:
Num: 12345
我想打印出输入的数字总和 (1+2+3+4+5 = 15):
total:15
我试过了,但是 for
循环中的 atoi()
有问题,我得到了一个错误:
[Error] invalid conversion from 'char' to 'const char*'
我该如何解决这个问题或如何以更简单的方式解决它?
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
char numstr[100];
int total = 0;
main(){
printf("Num:");
scanf("%s", numstr);
for(int i = 0; i < strlen(numstr); i++){
total += atoi(numstr[i]);
}
printf("%d", total);
}
您可以将数字字符(在 ASCII 中)减去 0x30(即 ASCII 字符零“0”),以将 ASCII 数字字符转换为其十进制等效值。
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
char numstr[100];
int total=0;
main(){
printf("Num:");
scanf("%s",numstr);
for(int i = 0;i<strlen(numstr);i++){
total += numstr[i] - 0x30;
}
printf("%d",total);
}
字符串“12345”将是
1 -> 0x31 - 0x30 = 1
2 -> 0x32 - 0x30 = 2
3 -> 0x33 - 0x30 = 3
4 -> 0x34 - 0x30 = 4
5 -> 0x35 - 0x30 = 5
我是一名优秀的程序员,十分优秀!