【发布时间】:2020-07-14 23:59:03
【问题描述】:
我正在尝试创建一个函数来扫描用户输入并显示计数的整数并将它们相加。例如,用户输入将是“12 街旁边的 2301 房间”,该函数会将数字 2301 计为 1,将 12 计为 2 并将它们相加,2313 是总和并返回它。所以返回将是 count=2, sum= 2313。但是,我对函数背后的逻辑有疑问。目前我的函数分别采用数字,例如。 2302 = 2,3,0,2。
这是我的代码:
void num_count(char array[]) {
int i = 0;
int count = 0;
int sum = 0;
int tmp[20];
tmp_size = 20;
while (array[i] != '\0') {
if (array[i] >= '0' && array[i] <= '9') {
tmp[i] = (array[i] - '0');
//not sure what to do here
count++;
sum += (array[i] - '0');
}
i++;
}
}
目前我尝试将其放入临时数组中,但不确定下一步该做什么。任何帮助将不胜感激。
【问题讨论】:
-
1.每个数字都是 10 的幂。相应地调整你的数学。
-
2.您可能应该使用
isdigit(),而不是array[i] >= '0' && array[i] <= '9' -
@RobertHarvey:我不是 100% 确定,但我怀疑
isdigit函数只不过是一个if块,例如:int isdigit(char c) { if (c >= '0' && c <= '9') return 1; else return 0; }。