【发布时间】:2017-04-21 12:17:05
【问题描述】:
对于我的作业,用户输入 5 个介于 1 和 9 之间的整数来表示五个 9 面骰子,然后用于计算分数。我们还需要能够检测无效输入,即 1-9 之间的 5 个整数以外的任何内容。问题是,当我为我的任务运行自动测试时,当输入少于 5 个东西时,我会收到运行时错误。
我的错误检查代码是(忽略 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在哪里初始化? -
哎呀,我的错,忘了把它放进去,虽然它已经初始化了
-
我无法重现您的问题...我运行代码并等待它获得 5 个元素。
-
是的,当我也尝试重现它时会发生这种情况,但自动测试不断出现
-
自动测试提供什么输入?
标签: c error-handling runtime-error scanf