我遇到了一个问题,我想遍历一个数组并检查是否只输入了正数。我知道可以使用 ctype.h 中的 isDigit,但我宁愿自己构造一些东西。我认为可行的方法是遍历数组的每个元素并查看存储在那里的值是否在 0 到 9 之间,但它不起作用。到目前为止,这是我的代码:
char testArray[11] = {'0'};
printf("Enter a string no longer than 10 chars");
scanf("%s", testArray);
int x;
int notanumber = 0;
for (x = 0; x < 11; x++) {
if ((testArray[x] < 0) || (testArray[x] > 9)) {
notanumber++;
}
}
printf("%i", notanumber);
最佳答案
它不起作用,因为 0
和 9
是整数而不是字符。
将您的 if
条件更改为
if((testArray[x] >= '0') || (testArray[x] <= '9')){ ... }
检查 0 到 9 的数字。
关于检查数组是否只包含数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20312518/