Stephen Fox
Stephen Fox

Reputation: 14470

C - Why is the answer 0.00000, when I try enter 3 numbers for the sum and average?

#include <stdio.h>

int main(int argc, char *argv[]) 
{

float num1 = 0;
float num2 = 0;
float num3 = 0;
float sum = num1 + num2 + num3;
float average = sum / 3;


printf("Enter three numbers:\n"); //Enter three floats
scanf("%f %f %f", &num1, &num2, &num3); //Assign to num1, num2, num3 

printf("The sum of these three numbers is %f.\n", sum);//Print sum
printf("The average of these numbers is %f.\n", average);//Print average

}

This is what is displayed.

Enter three numbers:

12.0

10.0

12.0

The sum of these three numbers is 0.000000.

The average of these numbers is 0.000000.

Upvotes: 0

Views: 530

Answers (3)

nanofarad
nanofarad

Reputation: 41281

Remember that C runs from top to bottom in a function without loops or conditionals.

You created num1, num2, and num3, as 0 each, and found their sum and average before inputting the numbers.

Do as follows:

float num1 = 0;
float num2 = 0;
float num3 = 0;
float sum = 0;
float average = 0;   

printf("Enter three numbers:\n"); //Enter three floats
scanf("%f %f %f", &num1, &num2, &num3); //Assign to num1, num2, num3 

sum = num1 + num2 + num3; //calculate
average = sum / 3;

printf("The sum of these three numbers is %f.\n", sum);//Print sum

printf("The average of these numbers is %f.\n", average);//Print average

Upvotes: 7

Vallabh Patade
Vallabh Patade

Reputation: 5110

C programs execute from top to bottom one instruction at a time. You have calculated sum and average before accepting the numbers. This evaluated to sum=0 and average=0 because all three numbers were 0.

main(int argc, char *argv[]) {
    float num1,num2,num3,sum,average;

    printf("Enter three numbers:\n"); //Enter three floats
    scanf("%f %f %f", &num1, &num2, &num3); //Assign to num1, num2, num3 

    sum = num1 + num2 + num3;
    average = sum / 3;

    printf("The sum of these three numbers is %f.\n", sum);//Print sum
    printf("The average of these numbers is %f.\n", average);//Print average
    return 0;
}

Upvotes: 10

LihO
LihO

Reputation: 42103

You seem to misunderstand the usage of variable definition. These:

float num1 = 0;
float num2 = 0;
float num3 = 0;
float sum = num1 + num2 + num3;
float average = sum / 3;

do not define the way the sum will be computed after the reading is done, but actually use these values and calculate the sum and average to be 0 before the program calls first scanf.

scanf("%f %f %f", &num1, &num2, &num3);
sum = num1 + num2 + num3;                     // <-- place it here
average = sum / 3;

Upvotes: 5

Related Questions