C Math assignment - c

I have to make a program that calculates the amount of coins needed to pay for something. I.E.
total cost = $1.35
$1.00 = 1, remaining $0.35
$0.25 = 1, remaining $0.10
$0.10 = 1, remaining $0.0
$0.05 = 0, remaining $0.0
$0.01 = 0, remaining $0.0`
My question is how do I do these math operations using modulus? as part of the assignment I have to do the calculations using modulus and integer division but i can't see how using modulus would work for this code. The code I started out with is the following
#include<stdio.h>
#include<math.h>
int main(){
float topay, change;
float gst = 1.13; //gst amount
int loonies, quatres, nickles, dimes, pennies; //coin variables
printf ("Please enter the amount to be paid: $");
scanf ("%f", &topay); //Input for amount to be paid
printf ("GST: %.2f\n", gst);
printf ("Balance owing: $%.2f\n", topay=topay*gst);
loonies = topay; //Math for amount of loonies
change = topay - loonies; //Math for balance owing
quatres = change/0.25; //Math for how many quarters needed
printf ("Loonies required: %d, balance owing $%.2f\n", loonies, change);
printf ("Quarters required: %d, balance owing $%.2f\n", quatres, change = change-(quatres*0.25));
return 0;
}

Modulus tells you the remainder following a division operation. So:
$1.35 modulus $1.00 yields 35 cents
So, you need to store 35 cents somewhere but also subtract it from the balance:
$1.35 - $0.35 = $1.00
Now you use integer division to see how many dollar coins in $1.00. Answer is one.
Okay, now the balance is $0.35. And the next coin is a quarter, $0.25.
So, $0.35 modulus $0.25 is $0.10. Store the ten cents.
Subtract $0.10 from the balance gives $0.25. How many quarters in $0.25? Answer one.
Okay, now the balance is $0.10.
And around you go.
This can be done in a simple loop with an array holding the coin denominations.

Related

Struggling to write a c program the runs the way this assignment is describing

so the assignment is like this:
"write one C program that asks the user to input the number of coins that the user has and then output the total amount of money the user has. Assume that the user has dimes, nickels, pennies and quarters only. After the user enters the number of coins for each denomination, the program should output the total amount of money. The program should work with any number of coins entered.
How many pennies do you have? 10
You entered 10
How many nickels do you have? 5
You entered 5
How many dimes do you have? 1
You entered 1
How many quarters do you have? 1
You entered 1
You have $0.70
Thank you."
The code i wrote looks like this:
#include<stdio.h>
#include<stdlib.h>
main() {
int pennyTotal, nickleTotal, dimeTotal, quarterTotal, result;
printf("How many pennies do you have?\n");
scanf_s("%i", &pennyTotal);
printf("How many nickles do you have?\n");
scanf_s("%i", &nickleTotal);
printf("How many dimes do you have?\n");
scanf_s("%i", &dimeTotal);
printf("How many quarters do you have?\n");
scanf_s("%i", &quarterTotal);
printf("You have\n");
result = pennyTotal + nickleTotal + dimeTotal + quarterTotal;
printf(result);
printf("Thank you.\n");
system("pause");
so far I got the "how many..." part right. It's just the part where I set the values and get the output to be how much money the user has when they enter a random number. I'm so lost but i feel like I'm really close.
Yes, you are close. The main problem you have is that printf(result); is wrong. You need printf("%d", result);

How to multiply variable correctly?

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.

C Program gets stuck in an infinite loop

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.

Monthly payments C program

Need some help with calculating the fixed monthly payment (P) required to fully amortize a loan of L dollars over a term of n months at a monthly interest rate of i. The given formula is: P = L[i(1 + i)n]/[(1 + i)n - 1]. I wrote a code but it didn't calculate Payment. I'm wondering if it is because I use double type together with int (for number of months) or the problem with formula?! Please help.
#include<stdio.h>
#include <math.h>
double calculatePayments(double rate, double loan, int payments);
int main() {
double principal, i, monthlyP;
int month;
printf ("Enter the principal amount: ");
scanf ("%f", &principal);
printf ("Enter the interest amount: ");
scanf ("%f", &i);
printf ("Enter the term in months: ");
scanf ("%d", &month);
monthlyP = calculatePayments (i, principal, month);
printf ("The monthly payment amount is %.2f: ", monthlyP);
return 0;
}
double calculatePayments(double rate, double loan, int payments) {
double mPayments;
mPayments = loan*(rate*(1 + rate)*payments)/((1 + rate)*payments - 1);
return mPayments;
}
Your scanf() requests %f format for a double; it should be %lf.
In addition to the need to fix the input (%lf instead of %f for doubles), I think your payment formula is wrong: since the future value of money grows exponentially, the formula should feature raising numbers to a certain power, which it does not.
The correct formula looks as follows (from here):
Since the loan needs to be paid off completely, FV is equal to zero.
Since pow(i+1, n) is used twice, it's a good idea to compute it once, and use the resultant variable in two places. The final version of this computation looks like this:
double calculatePayments(double rate, double loan, int payments) {
double mul = pow(1+rate, payments);
return (loan * mul * rate) / (mul - 1);
}
Demo on ideone computes the payment on $100,000 at 0.004% per month for 30 years at $524.67, which is the same value that excel's PMT function returns.
Note : When you enter the rate of 5.6% in your formula and in another calculator, don't forget that your formula takes the rate per month, not per year. Therefore, the rate that you plug into outside calculators must be 12 times what you enter into your calculator (for 5.6% annually you should enter 0.00466666
One of the first rules of debugging is to make sure you print the inputs to ensure that the program got the values you expected. It didn't, because you wrote:
scanf ("%f", &principal);
Since principal is a double, the format needs to be "%lf". Repeat for the interest rate. You should also check that the inputs succeeded:
if (scanf("%lf", &principal) != 1)
{
fprintf(stderr, "Failed to read principal\n");
return(1);
}
If you'd printed out the input values, you'd have known what was wrong immediately.
Read what dasblinkenlight said.
Also,
Fix your declarations and the variables you are using scanf() for.
principal should be loan. month should be payments.
i is okay. You need to calculate the monthly decimal number of the percentage given.
For instance,
interest = (i/100) /12;
Do that before your function call. Then just basically use dasblinkenlight's function at the bottom of your main.
hope you score a "10" ;)

while loop in C programing

Write a program that contains the loop
while (scanf("%1f", &salary) == 1) {...}
within the body of the loop compute a 17% federal withholding tax and a 3% state withholding tax and print these values along with the corresponding salary. Accumulate the sums of all salaries and taxes printed. Print these sums after the program exits the while loop.
My current code:
float salary, federal_tax, state_tax, salary_after_tax, salary_sum, tax_sum, salary_after_tax_sum;
printf("Enter Salary: $");
while (scanf("%lf", &salary) == 1)
{
salary_sum = salary;
federal_tax = salary*(.17);
state_tax = salary*(.03);
tax_sum = federal_tax + state_tax;
salary_after_tax = salary - federal_tax - state_tax;
salary_after_tax_sum = salary_after_tax;
printf("Salary before tax = %lf", salary);
printf("Federal tax = %lf", federal_tax);
printf("State tax = %lf", state_tax);
printf("Salary after tax = %lf\n", salary_after_tax);
break;
}
printf("total salary before tax = %lf", salary_sum);
printf("total tax = %lf", tax_sum);
printf("total salary after tax = %lf\n", salary_after_tax_sum);
system ("pause");
return 0;
}
For some reason it doesn't work. Any help would be appreciated.
Your scanf specifier is %lf (your problem statement says %1f instead, is that intentional?) and yet you're storing into a float. My scanf(3) says %lf specifies a double.
Incidentally, float has much less precision than many programmers may expect, just about seven digits, so using double instead is probably a good idea for salaries.
You should assign your ..._sum variable to 0 outside the loop, and increment them with += in the loop; what you're doing now instead is reassigning them every time through the loop, and that isn't summing!-)
You lied to the compiler and it got its revenge: the %lf format needs to go with a pointer-to-double, while you provide only a pointer-to-float. This means undefined behavior in C lingo (anything may happen).
Fix your float declarations by turning them into doubles.

Resources