'What is incorrect about this code? Its written in C
This code keeps giving the package weight must be greater then 0 output no matter what I input. How would I go about fixing this issue.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
double packageWeight = 0.0;
const double TWOPOUNDS = 1.25;
const double LESSSIX = 2.50;
const double LESSTEN = 3.90;
const double OVERTEN = 4.40;
double shippingCost = 0.00;
printf("Enter the weight of the package: ");
scanf("%.1lf", &packageWeight);
if (packageWeight <= 2) {
shippingCost = TWOPOUNDS;
}
else if (packageWeight <= 6) {
shippingCost = LESSSIX;
}
else if (packageWeight <= 10) {
shippingCost = LESSTEN;
}
else if (packageWeight >= 10) {
shippingCost = OVERTEN;
}
if (packageWeight <= 0) {
printf("The weight of the package must be greater than 0.00.\n");
}
else if (packageWeight > 0) {
printf("The shipping charge is $%.2lf.\n", shippingCost);
}
return 0;
}
Solution 1:[1]
anyway , your scanf is wrong, corrected below. Plus you should be dealing with invalid input
while (true) {
printf("Enter the weight of the package: ");
int ret = scanf("%lf", &packageWeight);
if (ret == 1)
break;
int c;
while ((c = getchar()) != '\n' && c != EOF);
}
the extra logic detects if the user enters say, 'dunno' at the prompt
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
