Variable Multiplication in C?
-
01-10-2019 - |
Question
//Hydroelectric Dam Helper
#include <stdio.h>
#define GRAV 9.80
#define EFINC 0.9
#define EFINC2 90
int main()
{
//Defines all the variables to be used
double height, work, mass;
printf("Height of dam (in meters):");
scanf("%lf", &height);
printf("Flow of water (in thousand cubic meters per second):");
scanf("%lf", &mass);
work = (mass * GRAV * height * EFINC);
printf("The dam would produce %f megawatts at %d%% efficency", &work, EFINC2);
return 0;
}
The values set correctly, I tested it by having it print height and mass but work never receives a value, and EFINC2 prints out a ridiculous number that I'm not really sure about
Solution
printf("The dam would produce %f megawatts at %d%% efficency", &work, EFINC2);
should read:
printf("The dam would produce %f megawatts at %d%% efficency", work, EFINC2);
&work
is a pointer to work, i.e. a double*
but for printf
to print the value you need to pass a double
and not a pointer. On your platform a double*
is probably a different size to a double
causing the subsequent printf
formats to use the wrong data.
OTHER TIPS
The problem is that you are having printf output a float
with the %f
specifier but passing in a double*
via &work
. Just remove the &
and it should work fine.
printf("The dam would produce %f megawatts at %d%% efficency", work, EFINC2);
The reason why you are receiving a "ridiculous number" is that you are passing the address of work
to printf()
. Change &work
to work
and it should work properly.
Sure. The ampersand &
in the printf-line means that the address of the variable work
is read instead of the value
Try appending a d to the constants to force c to not cast to int might work. You could also try explicitly casting the values to either float or double.
you have given &work which is the address of work variable in memory, so it doesn't print any absurd value, it prints the memory location of work.
You should remove & from &work to receive value of work variable.
printf("The dam would produce %f megawatts at %d%% efficency", work, EFINC2);