问题:我正在做一个看似非常简单的任务,但是,我收到的错误是变量' test1'没有初始化。我将它声明为int,然后在scanf语句中初始化它。这里有什么帮助吗?
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
void main()
{
int hours, hours2, test1, test2, test3, avg, well;
avg = (test1 + test2 + test3) / 3;
printf("Enter your Cprogram Test grades here for Test 1, 2, and 3: \n");
scanf("%d%d%d", &test1, &test2, &test3);
printf("The average of these grades are: %d. \n", avg);
答案 0 :(得分:4)
您在行
中使用了变量lsof -P | grep ':3000' | awk '{print $2}' | xargs kill -9
kill -9 $(lsof -t -i:3000)
来自之前 scanf。因此,test1
(以及同样avg = (test1 + test2 + test3) / 3;
和test1
)在当时使用时未初始化。
答案 1 :(得分:0)
通过从scanf读取初始化后,需要计算引用test1的avg = (test1 + test2 + test3) / 3;
。在scanf("%d%d%d", &test1, &test2, &test3);
之后移动该行,它将起作用:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
void main()
{
int hours, hours2, test1, test2, test3, avg, well;
printf("Enter your Cprogram Test grades here for Test 1, 2, and 3: \n");
scanf("%d%d%d", &test1, &test2, &test3);
avg = (test1 + test2 + test3) / 3;
printf("The average of these grades are: %d. \n", avg);
}
C,C ++,与大多数过程语言一样,按照编写顺序对代码进行评估。也就是说,avg = (test1 + test2 + test3) / 3;
根据test1,test2和test3的当前值为avg分配值。必须在执行分配之前定义和初始化这些。这就是scanf("%d%d%d", &test1, &test2, &test3);
的作用。