Reputation: 125
I am writing this code that calculates Miles per Gallon where the number of miles and gallons are read from the keyboard. The program will perform a simple calculation to get the miles per gallon. I wrote a function in order to do this this calculation but it is not returning the result. Inside the function everything is working as it should. I even wrote a printf
to ensure the calculation was done correctly. But then when I try to return it to the main function, the member of the structure appears to have a value of 0
instead of the result of the calculation. Here is my code:
#include <stdio.h>
#include <stdlib.h>
struct gas {
float distance;
float gals;
float mpg;
};
float CalculateMpg(struct gas idk){
idk.mpg = idk.distance / idk.gals;
printf("%f \n", idk.mpg);
return idk.mpg;
}
int main()
{
struct gas idk;
printf("Enter distance (in miles): ");
scanf("%f", &idk.distance);
printf("Enter gallons fueled: ");
scanf("%f", &idk.gals);
CalculateMpg(idk);
printf("%f \n", idk.mpg);
printf("Miles driven gallons used with %.2f miles and %.2f gallons: %.2f mpg \n", idk.distance, idk.gals, idk.mpg);
return 0;
}
Upvotes: 0
Views: 39
Reputation: 987
Reason: Because C uses call-by-value
When you call function CalculateMpg()
, idk is copied to argument variable by value.
In this function, only copied argument is edited.
You should make function uses pointer and call it to CalculateMpg(&idk)
Sample Solution:
#include <stdio.h>
#include <stdlib.h>
struct gas {
float distance;
float gals;
float mpg;
};
float CalculateMpg(struct gas* idk){
idk->mpg = idk->distance / idk->gals; // arrow is just syntactic sugar of (*idk).field
printf("%f \n", idk->mpg);
return idk->mpg;
}
int main()
{
struct gas idk;
printf("Enter distance (in miles): ");
scanf("%f", &idk.distance);
printf("Enter gallons fueled: ");
scanf("%f", &idk.gals);
CalculateMpg(&idk);
printf("%f \n", idk.mpg);
printf("Miles driven gallons used with %.2f miles and %.2f gallons: %.2f mpg \n", idk.distance, idk.gals, idk.mpg);
return 0;
}
Upvotes: 1