Order of operation question

0 Marcus Sinclair · October 10, 2014
Why does this work?
int main()
{
float a;
float b;
float c;
float avg;



printf("Enter a value for a:\n");
scanf(" %f",&a);
printf("Enter a value for b:\n");
scanf(" %f",&b);
printf("Enter a value for c:\n");
scanf(" %f",&c);
avg= (a + b + c) / 3;
printf("The average age is %.2f",avg);



return 0;
}

but when I change the equation of avg to the following it does not?

int main()
{
float a;
float b;
float c;
float avg;
avg= (a + b + c) / 3;


printf("Enter a value for a:\n");
scanf(" %f",&a);
printf("Enter a value for b:\n");
scanf(" %f",&b);
printf("Enter a value for c:\n");
scanf(" %f",&c);

printf("The average age is %.2f",avg);



return 0;
}




Post a Reply

Replies

Oldest  Newest  Rating
0 Marcus Sinclair · October 10, 2014
You misunderstood my question. All I did is move the equation I'm trying to understand why it makes a difference where I place it.
+1 Горан Куга · October 14, 2014

You misunderstood my question. All I did is move the equation I'm trying to understand why it makes a difference where I place it.


Hi buddy, check comments in next code. If you have any questions please ask.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>

int main()
{
    float a;
    float b;
    float c;
    float avg;
    
   avg= (a + b + c) / 3; // if you put your equation here its not gonna work as it should. Your program works from top to bottom so if you put your equation here in this line it will do next. avg = (0 + 0 + 0) / 3. Why are a, b and c 0 and not what user types. Its because your program works from top to bottom user never had a chance to enter values for floats a, b or c. Your floats a, b, c are currently 0 so the result of this equation is gonna be 0 your float avg is now 0.

    printf("Enter a value for a: \n");
    scanf(" %f", &a);
    printf("Enter a value for b: \n");
    scanf(" %f", &b);
    printf("Enter a value for c: \n");
    scanf(" %f", &c);
    
    avg= (a + b + c) / 3; // and if you put your equation here its gonna work as it should because user entered value for a, b and c and after thats done computer is gonna solve the equation. Let's say user entered 5 for a, 5 for b and 4 for c. avg = (5 + 5 + 4) / 3. avg = 14 / 3, avg = 4.67
    
    printf("The average age is %.2f", avg);
    
    return 0;
}
+1 Marcus Sinclair · October 14, 2014
Thanks that is exactly the info I was after.
  • 1

C

107,056 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator