[英]A function returns different values in every execution
我在編碼方面有些新手,遇到了邏輯錯誤。 目標是創建一個 function 來測試數字是否可以從 2 到 10 整除。但是,正如我測試的那樣,userInput 變量返回正確的值,但是 function 的值在每次執行時都會改變。 這是代碼:
#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
在你的代碼中,
int checker;
是一個自動局部變量,未顯式初始化。 因此,它包含的初始值indeterminate 。
您必須將該值初始化為0
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.