對於我的任務,用戶輸入1到9之間的5個整數來表示5個9面的骰子卷,然後用它們計算得分。我們還需要能夠檢測和無效輸入,即1-9之間的5個整數以外的任何內容。問題是,當我爲我的任務運行自動測試時,當輸入少於5件事情時,出現運行時錯誤。使用scanf進行錯誤檢查
我的錯誤校驗碼(忽略countArray的事情,在程序是爲以後):
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define ARRAY_SIZE 5
...
int main(void) {
int numbers[ARRAY_SIZE];
int scanFail = 0;
int i = 0;
...
// Check for if 5 integers between 1 and 9 have been entered
while (i < ARRAY_SIZE && scanFail == FALSE) {
if (scanf("%d", &numbers[i]) != 1) {
scanFail = TRUE;
}
if (numbers[i] < 1 || numbers[i] > 9) {
scanFail = TRUE;
}
countArray[i] = ARRAY_NOT_COUNTED;
i++;
}
if (scanFail == TRUE) {
printf("Invalid Input: 5 integers 1..9 must be supplied.\n");
return EXIT_FAILURE;
}
...
這是自動測試說:
Test10 (1 2 3) - failed (errors)
Your program produced these errors:
Runtime error: uninitialized variable accessed.
Execution stopped here in main() in youChew.c at line 65:
\t\t}
\t\t
-->\t\t if (numbers[i] < 1 || numbers[i] > 9) {
\t\t scanFail = TRUE;
\t\t}
Values when execution stopped:
i = 3
numbers = {1, 2, 3, 69513217, -22336628}
scanFail = 1
numbers[i] = 69513217
Test 11 (potato) - failed (errors)
Your program produced these errors:
Runtime error: uninitialized variable accessed.
Execution stopped here in main() in youChew.c at line 65:
\t\t}
\t\t
-->\t\t if (numbers[i] < 1 || numbers[i] > 9) {
\t\t scanFail = TRUE;
\t\t}
Values when execution stopped:
i = 0
numbers = {69515968, 0, 8192, 69513217, -18240628}
scanFail = 1
numbers[i] = 69515968
我不是真的確定如何解決它,所以任何幫助表示讚賞。
'i'在哪裏初始化? – Marievi
哎呦我的壞,忘了把它,它是初始化雖然 – Raze
我不能再現你的問題......我運行的代碼,它等待,直到它得到5個元素。 – Marievi