我在编码方面有点新,我遇到了一个逻辑错误。目标是创建一个函数来测试数字是否可以从2整除到10。然而,正如我测试过的那样,userInput变量返回正确的值,但是函数的值确实改变了每次执行。以下是代码:
#include <stdio.h>
int testDivisible(int a) {
int checker; // checker is intended for counting divisible numbers between 2-10; if returned > 0, then not divisible
for (int i=2; i<=10; i++) {
if (a % i == 0) {
checker = checker + 1;
}
}
return checker;
}
int main() {
int userInput;
printf("Enter number: ");
scanf("%d", &userInput);
int x = testDivisible(userInput);
if (x > 0) {
printf("Is divisible by 1 to 10\n");
}
else {
printf("Is not divisible by 1 to 10\n");
}
printf("%d\n", userInput); // intended for testing
printf("%d", x); // intended for testing
}但是,当我编译和运行代码时,结果是:
执行1:
Enter number: 17
Is divisible by 1 to 10
17
847434400执行2:
Enter number: 17
Is not divisible by 1 to 10
17
-1002102112发布于 2021-09-30 14:55:23
在你的代码中,
int checker; 是一个自动局部变量,没有显式初始化。因此,它在indeterminate.中包含的初始值
必须将值初始化为0。
https://stackoverflow.com/questions/69394428
复制相似问题