Reputation: 59
Trying to make a simple program that calculates the amount of weight lost over a given amount of days using a constant variable. Everything looks right to me but it's outputting 0 as the answer? Any help would be much appreciated!
#include <stdio.h>
#include <stdlib.h>
int main(){
double days; //declaring variables that will be enetred by user
const float weightLoss = 0.04; //declaring constant to be used in calculation
float overallLoss; //float that is used to display overall result
printf("Please enter how many days you are going to fast for: \n");
scanf("%f", &days); //scans keyboard for input and assigns to designated variable
printf("You entered: %f\n", days);
overallLoss = days * weightLoss;
printf("You will lose %.2f stone", overallLoss); //print of the final result
}
Upvotes: 0
Views: 64
Reputation: 753705
You have double days;
, so you need scanf("%lf", &days)
. Or you can use float days;
with the current format.
With printf()
, you don't need the l
; with scanf()
, it is crucial.
Don't forget to end outputs with a newline; your last printf()
is missing one. Also, some compilers (GCC and clang, for example) will provide warnings about such mismatches between the format string and the types provided. Make sure you're using the appropriate options (gcc -Wall
, for example) to get them diagnosed.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
double days;
const float weightLoss = 0.04; // Dimension: stone per day
float overallLoss;
printf("Please enter how many days you are going to fast for: ");
if (scanf("%lf", &days) != 1)
{
fprintf(stderr, "Oops!\n");
exit(1);
}
printf("You entered: %13.6f\n", days);
overallLoss = days * weightLoss;
printf("You will lose %.2f stone\n", overallLoss);
return 0;
}
First run:
Please enter how many days you are going to fast for: 12
You entered: 12.000000
You will lose 0.48 stone
Second run:
Please enter how many days you are going to fast for: a fortnight
Oops!
You can forego the if
test if you've not learned about those yet as long as you type the input accurately; it must be a recognizable number.
Using float days
instead of double days
.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
float days;
const float weightLoss = 0.04; // Dimension: stone per day
float overallLoss;
printf("Please enter how many days you are going to fast for: ");
if (scanf("%f", &days) != 1)
{
fprintf(stderr, "Oops!\n");
exit(1);
}
printf("You entered: %13.6f\n", days);
overallLoss = days * weightLoss;
printf("You will lose %.2f stone\n", overallLoss);
return 0;
}
Please enter how many days you are going to fast for: 10
You entered: 10.000000
You will lose 0.40 stone
Upvotes: 4