我正在编写一个函数,将来自用户的输入作为字符数组,并在对它们求和的同时查看其数量(例如0123456789将为count = 10,sum = 45)
问题是,如果用户输入了“ welcome to 123 street”之类的数字,计数和总和均为0。当输出应为count = 3时,sum = 6。
我使用的方法是检查char数组的索引是否大于或等于零且小于或等于9(ASCII值)。
以下是该函数的代码:
int count = 0;
int sum = 0;
int i = 0;
void num_count(char array[]) {
while (array[i] != '\0') {
if (array[i] >= '0' && array[i] <= '9') {
count++;
sum += (array[i] - '0');
}
i++;
}
}
不确定是否需要发布主要功能。
答案 0 :(得分:1)
您可能多次调用了该函数,并且在全局范围内定义的变量i
,count
和sum
并未重新初始化。
尝试:
int count = 0;
int sum = 0;
void num_count(char *array) {
int i;
count = 0;
sum = 0;
for (i = 0; array[i] != 0; i++) {
if (array[i] >= '0' && array[i] <= '9') {
count++;
sum += (array[i] - '0');
}
}
}
正如@tadman指出的那样,您不应以这种方式使用全局变量。由于只能从该函数返回一个值,因此可以将另一个用作参数:
/**
* Function to count digits.
*
* @param char * array array to be counted
* @param int * sum where the sum is stored
*
* @return int number of numeric characters found
*/
int num_count(char *array, int *sum) {
int i;
count = 0;
*sum = 0;
for (i = 0; array[i] != 0; i++) {
if (array[i] >= '0' && array[i] <= '9') {
count++;
*sum += (array[i] - '0');
}
}
return count;
}
您将其称为
int count, sum;
count = num_count(string, &sum);
printf("Count is %d, sum is %d\n", count, sum);
这使所有代码都可以“驻留”在单个函数中,而不会剩下任何部分(总和和计数),更糟糕的是,可能会被需要相同变量的其他函数覆盖或与之冲突。
主模块只需要知道该函数的调用方式,因此(通常在main.h或类似的东西中)您将具有该函数的 prototype 及其说明: / p>
int num_count(char * array,int * sum);