I'm writing code that reads the input for water consumption and displays the bill. the fixed price is $10. for the first 30 meters it costs $0.6 per meter, for the next 20 meters it costs $0.8, then the next 10 meters it cost $1.2 per meter and additional meters are $1.2 but for some reason my code asks the user to input a value and does nothing else. what am I doing wrong? Is it my if statements? I feel as though they are okay and my calculations may be the problem. here is the code so far:
#include <stdio.h>
int main()
{
int watercom, fixedrate, first30, next20, next10, additional, firstcal, secondcal,thirdcal, fourthcal;
printf("what is our water consumption?\n");
scanf("%i\n",&watercom);
fixedrate = 10;
first30 = 0.6;
next20 = 0.8;
next10 = 1.0;
additional = 1.2;
firstcal = fixedrate * first30;
secondcal = fixedrate * next20;
thirdcal = fixedrate * next10;
fourthcal = fixedrate * additional;
if ( watercom <= 30)
printf("your bill is %i", &firstcal);
else if (watercom >= 31 && watercom <= 50)
printf("your bil is %i", &secondcal);
else if (watercom >= 51 && watercom >= 60)
printf("your bill is %i", &thirdcal);
else if (watercom >= 61)
printf("your water bill is %i", fourthcal);
return 0;
}
if ( watercom <= 30)
printf("your bill is %i", &firstcal);
else if (watercom >= 31 && watercom <= 50)
printf("your bil is %i", &secondcal);
else if (watercom >= 51 && watercom >= 60)
printf("your bill is %i", &thirdcal);
else if (watercom >= 61)
printf("your water bill is %i", fourthcal);
There are a number of simplifications that can be applied:
You don't need the >= part in each if statement as if watercom <= 30 then it is implicitly >= 31.
Also you don't pass in the address-of (&) values to printf, you pass in the values directly.
You also don't have a default case for when watercom is outside the range of expected values:
if ( watercom <= 30 )
printf("your bill is %i", firstcal);
else if ( watercom <= 50)
printf("your bill is %i", secondcal);
else if ( watercom <= 60)
printf("your bill is %i", thirdcal);
else
printf("your water bill is %i", fourthcal);
In addition to what others have pointed out, all your variables are int but some need to be double [because you're setting them to 0.6, etc.]:
int watercom;
double fixedrate;
double first30;
double next20;
double next10;
double additional;
int firstcal;
int secondcal;
int thirdcal;
int fourthcal;
Yeah your only int is fixedRate. The rest are floats.
Also by what you say in your question that is not what is in your program. If the fixedRate is 10 and the first 30 is at a rate of .6 then if I input 30 I should get fixedRate + (30*.6).
You need to add the fixedRate to all calculations and add the calculations for each tier together for your final amount.
Work the problem on paper before you try to write the program. You should know what output is expected before you test your program.
😊Happy Day!
The algebra of the calculations, as they appeared in the first version of this post, seems all wrong to me. To get you started on that: as well as these amount * rate multiplications, you need to be performing an addition --- a fixed rate term, plus another amount if you go over the initial allowance, plus another amount when you enter the next price bracket, and so on. To calculate each of these terms, you need to be subtracting the amount of water already-paid-for in previous terms as you go along.
But that's not the question. You asked why the program was not printing anything at all. For me, after making a command-line executable out of this using Visual Studio on Windows, I did replicate that problem: I input the value, then nothing seems to happen. But then the answer is finally printed when I press control-C to halt the program.
To fix this, remove the \n from the scanf command.
Then proceed to your other problems, which include (a) getting the algebra right, and (b) printing the value (e.g. firstCal) not the address (&firstCal) of your variables.
Related
#include <stdio.h>
int main(){
double km, miles, yards, feet, inches;
scanf("%lf", &km);
miles = km/1.609;
printf("%d\n", (int)miles);
yards = ((km*1093.61) - ((int)miles*1760));
printf("%d\n", (int)yards);
feet = (km*3281.4) - ((int)miles*5280 + yards*3);
printf("%d\n", (int)feet);
inches = km*39378.498 - ((int)miles*63360 + (int)yards*36 + (int)feet*12);
printf("%.2lf", inches);
return 0;
}
This is what I managed to write, however it still doesn't pass all tests and isn't 100% accurate as seen in the image below
Help would be highly appreciated.
When writing code to do conversions such as in your task, it is better to do all (internal) calculations in double precision and convert each component part of the result (to int) 'on the fly', then subtract each of those converted values as they are determined.
So, first get the conversion into miles as a double value, then subtract each integral part and multiply the remainder by the factor required to get the next sub-unit. Using this approach, you are far less likely to encounter problems due to integer overflow and rounding errors.
The following is a potential solution. (Note that it is far better to write clear code than attempt to 'compress' many operations into single-line code; the latter is a common cause for bugs creeping into your code and also makes it more difficult for future developers of your code to understand and/or modify it.)
#include <stdio.h>
int main()
{
double km = -1.0, total, inches;
int miles, yards, feet;
do {
printf("Enter value in Km: ");
if (scanf("%lf", &km) != 1) { // Error input: clear buffer
int c;
while ((c = getchar()) != '\n' && c != EOF)
;
if (c == EOF) return 1; // Can't do much after an EOF!
}
} while (km < 0.0);
// First, do the conversion to double "total" ...
total = km / 1.609;
// Now, get the integer "miles" value and subtract that from the total ...
miles = (int)total;
total -= (double)miles;
// Next, multiply remainder by 1760 to get the number of yards ...
total *= 1760.0;
// Now, get the integer value and subtract that from total ...
yards = (int)total;
total -= (double)yards;
// Multiply remainder by 3 to get feet ...
total *= 3.0;
feet = (int)total;
total -= (double)feet;
// Finally, multiply remainder by 12 to get inches ...
inches = total * 12.0;
// Display result:
printf("%d %d %d %.2lf\n", miles, yards, feet, inches);
return 0;
}
Note that I have also added some code to check that the input value is 'acceptable' (I have chosen to reject negative values, but you can easily change that condition); more importantly, the code will also be able to deal with situations where the user enters a value that cannot be interpreted as a floating-point input (like "Fred"). When using scanf for user input, it is always a good idea to check for valid input and handle possible error conditions.
Im making a shipping calculator that ask how many pounds your item weighs. If it weighs less than 50 pounds the charge is 6.00. If it weighs 50 pounds but less than 100 pounds the charge is 10.50. The shipping charge also doubles for every 1000 miles. Im having a problem figuring out how to make the calculator double if user inputs over 1000 miles.
int main()
{
double weight, distance, charge;
printf("Enter your package weight: \n");
scanf("%lf", &weight);
printf("How far are you sending the package? \n");
scanf("%1lf", &distance);
if(weight <= 50)
charge = 6;
else
if(weight <= 100)
charge = 10.50;
printf("Shipping charge: %.2lf\n", charge);
}
When I run the program I dont get the correct shipping charge.
Maybe you should printf the charge instead of the weight?
In your code you are outputting weight in the end and not the charge, the one that was actually mutated.
I just started C programming with cs50.
I tried to do the problem set about the greedy algorithm but can't seem to find the bug. My code is below.
#include <cs50.h>
#include <stdio.h>
#include <math.h>
int main (void)
{
int count = 0;
printf("how much is the change?: ");
float change = get_float();
while(change < 0)
{
printf("change is to be more than 0");
change = get_float();
}
int amount = lroundf(change*100);
while(amount > 0)
{
if ((amount-25) >= 25)
{
amount = amount - 25;
count++;
}
else if ((amount-10) >= 10)
{
amount = amount - 10;
count++;
}
else if ((amount-5) >= 5)
{
amount = amount -5;
count++;
}
else if((amount-1) >= 1)
{
amount = amount -1;
count ++;
break;
}
else
{
printf("you have no change \n");
}
}
printf("your number of coins is %i\n", count);
}
When I input my change as 1, I am given back 8 coins. Can't seem to find where the bug is. Can anyone help me?
Firstly, you could try running your program with values for change that return simple answers, like 1 coin, using, for example, change = 0.25. If that works, then you should start trying with some few coins, repeating one type, like you did with 1.00, or joining a few types, like 0.06 . And after that, try big numbers and values with higher floating inaccuracy, like 4.10. Following this should lead you to your answers.
If, after trying that, you still can't find the problem, then here is the answer: the problem is with the if/else if expressions. When you are trying to count the quarters, for example, the (amount-25) >= 25 doesn't work properly. You're trying to take away a quarter while amount is bigger or equal to 25, but your code just do that until it gets to less than 50. Developing your expression may help you see it: (amount-25) >= 25 -> (amount-25) + 25 >= 25 + 25 -> amount >= 50.
Another problem you may find is with that break statement. It might get out from the loop earlier than expected. If you try running numbers like 0.04 and 0.03 you'll see the count stuck at 1. After removing the first penny, the code breaks out of the loop leaving amount still bigger than 0. breaks make it harder to see when the code is getting out of the loop and that's why many programmers recommend avoiding it whenever possible.
I am in programming 1 right now. I am creating a program that is meant to show the calculation of a teachers discount (12%) on a total purchase amount. When printing the amount of the discount on screen based on purchase total, I am coming up with an incorrect total. Here is the Code:
double total_b4_tax;
printf("\nEnter the purchase total : ");
scanf("%lf", &total_b4_tax);
getchar ();
if (teach_music == 'y' || 'Y')
{
double discount_total = teach_music * .12;
printf("Total purchase $ %.2lf\n", total_b4_tax);
printf("Discount total $ %.2lf\n", discount_total);
}
My discount total is coming to 14.52 when in actuality 122.0 * .12 is 14.64. How do I solve this issue?
You are trying to calculate a discount by multiplying a character with a float:
double discount_total = teach_music * .12;
before that, you made sure that teach_music is 'y' or 'Y'. Im curious how that compiled, and how C comes to the conclusion that 'y' or 'Y' is 121.
EDIT: Harr, 'Y' is ASCII 121. So multiplying that with .12 results in 14.52
Anyway, I assume that
double discount_total = total_b4_tax * .12;
makes it all better.
The problem I've been having is that my code will get stuck either in an infinite loop or will have a stack overflow problem and begin producing negative numbers during calculations.
I am aware that this issue is coming from my while loop and also think the issue probably lies with the formula I am using being the line i = (r / 12)*(b - p + temp);.
However I am unsure of how to fix this. My formula is trying to calculate the interest paid on a fixed interest loan for each month over 12 months and print that to the screen with the remaining balance. This is supposed to continue until the balance reaches 0.
#include <stdio.h>
// main function
int main()
{
// variable declarations
float r = 0.22; // interest rate
float b = 5000.0; // amount borrowed
float p; // payment amount
int m = 1;
float temp, ti = 0;
float i;
// Take in data from user
printf("Please enter the amount you wish to pay monthly: \n");
scanf("%f", &p);
printf("\n");
//display interest rate, initial balance, monthly payment
printf("r = %.2f\nb = %.1f\np = %.1f \n\n", r, b, p);
// Month by month table showing month interest due/paid and remaining balance
i = (r / 12) * b;
temp = i;
printf("%d %.2f %.2f\n", m,i,b);
m++;
while (i > 0) {
i = (r / 12) * (b - p + temp);
b = (b - p + temp);
ti += temp;
temp = i;
printf("%d %.2f %.2f\n",m, i, b);
m++;
}
printf("\n");
printf("total interest paid: %.2f\n", ti);
return 0;
}
Well, if I'm doing the math correctly it looks like if you enter a value less than 91.67 for P you are going to get stuck in an infinite loop because the monthly payments are less than the interest accusing on the debt; so you might want to add a check for that.
As an aside if you named your variables as Interest, Base, etc. you wouldn't need the comments and the code would be easier to read.
Also since you are printing out the payment info until balance is zero you should loop while b > 0.
The program works as expected.
The only problem is, if your monthly payment are less
than the interest rate - then the amount you need to pay back
grows exponentially and the program never stops.
Enter any number >= 92 and it seems to work.
Is 22% p.a. interest rate correctly?
I don't see this generating an infinite loop but it would become a problem if your repayment is higher than the matured interest, which with your starting parameter it means anything below 91.67.
You may have a wrong end condition so there is always a negative line printed, though.