-3

从 Windows 开始,我开始使用 linux 编写 C 语言。

我的问题是如何停止或重置计算。

像这里:(示例)

#include <stdio.h>
#include <conio.h>

main(){
    int average;
    int total;
    int number;
    int loopcount;
    loopcount=0;
    system("clear");
    while(loopcount<3){
        printf("Enter a number:");
        scanf("%d",&number);
        total=total+number;
        loopcount=loopcount+1;
    }
    average=total/3;
    printf("the average is %d", average);
    getch();
}

输出:输入一个数字:1 输入一个数字:1 输入一个数字:1 平均值是 1。但是当我再次运行它时,最后计算的平均值会添加到我的新平均值中。我应该如何或在我的代码中输入什么来阻止这种情况。

? 我试过谷歌,但找不到确切的关键字。天呐!

4

3 回答 3

5

total未初始化,因此未指定其初始值。

将其初始化为 0 可能会解决您的问题。

于 2013-07-28T13:59:01.460 回答
1

您没有初始化total- 您必须在函数中分配0自己main(因为变量位于堆栈上)。

但是您的代码中有很多异味-我将其重写为以下内容。

注意还删除了conio.h包括,Linux 编译器不支持它,因为它在 MS 和其他一些编译器中是非标准扩展!

#include <stdio.h>

int main(){
    system("clear");
    int total = 0;
    for (int loopcount = 0; loopcount < 3; ++loopcount) {
        int number;
        printf("Enter a number:");
        scanf("%d", &number);
        total += number;
    }
    int average = total  / 3;
    printf("the average is %d", average);
    getchar();
    return 0;
}

total还要注意不能被 3 整除时的舍入误差-int除法返回integers

编辑:如果你想用普通的旧 C89 编译它,你应该替换

for (int loopcount = 0; loopcount < 3; ++loopcount) {

int loopcount;
for (loopcount = 0; loopcount < 3; ++loopcount) {

或者,如果您更喜欢更新的 C99 或更好的 C11 编译-std=c99-std=c11编译器选项。

于 2013-07-28T13:59:13.080 回答
0

在计算中使用它之前尝试将 total 初始化为零:

#include <stdio.h>
#include <conio.h>

main(){
    int average;
    int total;
    int number;
    int loopcount;
    loopcount=0;

    total = 0;  /* Added */

    system("clear");
    while(loopcount<3){
        printf("Enter a number:");
        scanf("%d",&number);
        total=total+number;
        loopcount=loopcount+1;
    }
    average=total/3;
    printf("the average is %d", average);
    getch();
}

分享和享受。

于 2013-07-28T13:58:58.533 回答