Im trying to write this code for school, and im absoultly stuck on what im doing wrong, if anyone could just point me in the right direction, that would be helpful. Trying to learn as much as i can.
My program doesnt calculate out, how much is owed at the end of each month, after subtrackting the payment, and then adding the interest.
IT just displays the same value.
#include<stdio.h>
int main()
{
float loan;
float interest;
int n;
float outstanding;
float outstanding2;
float princeable;
float payment;
printf("\nEnter the amount of the loan: \n ");
scanf("%f" , &loan);
printf("\nEnter monthly interest percentage\n ");
scanf("%f" , &interest);
printf("\nEnter monthly payments: \n ");
scanf("%f" , &payment);
printf("\nEnter number of monthly Payments: \n ");
scanf("%i" , &n);
while (n >= 0) {
outstanding = (loan - payment);
outstanding = (outstanding * (1 + (interest/100)));
printf("\Outstanding Balance after %i =%.2f\n\n", n, outstanding);
n--;
}
return 0;
}
In each iteration, you should calculate outstanding based on its previous value, and not on the initial loan's value, because you also pay interest for interest.
outstanding = loan;
while (n > 0) {
outstanding = (outstanding - payment);
outstanding = (outstanding * (1 + (interest/100)));
printf("\Outstanding Balance after %i =%.2f\n\n", n, outstanding);
n--;
}
This line:
outstanding = (loan - payment);
within the loop is incorrect since it starts with the initial loan value each time. It should be:
outstanding = (outstanding - payment);
You'll also have to set outstanding to loan before entering the loop.
On top of that, you have one too many loop iterations, and an illegal escape sequence \O in your printf string.
Related
From what I understand I should be getting 3 user input prompts, Trip Distance, Car MPG, and Gas Dollars Per Gallon to calculate total trip cost. Whenever I run the code, I only get prompted to input trip distance and car mpg, it skips gas dpg. How do I get it to recognize 3 user inputs?
int main() {
int miles;
double milesPG;
double dollarsPG;
double gasCost = (miles * (1.0 / milesPG) * dollarsPG);
printf("Input trip distance: ", miles);
scanf("%d", &miles);
printf("\nInput car miles per gallon: ", milesPG);
scanf("%0.2lf", &milesPG);
printf("\nInput gas dollars per gallon: ", dollarsPG);
scanf("%0.2lf", &dollarsPG);
printf("\nTotal trip cost is %0.2lf \n", gasCost);
return 0;
}
There are multiple problems in your code:
you do not include <stdio.h>
you compute gasCost before the values of miles, milesPG and dollarsPG are input. Since these variables are uninitialized, this has undefined behavior.
passing the uninitialized values to the printf() statements for prompting is useless and actually has undefined behavior as these variables are uninitialized.
the conversion format "%0.2lf" is invalid for scanf(). You cannot specify how many places to input, just the maximum number of bytes to read, which is not useful in your case.
Here is a modified version:
#include <stdio.h>
int main() {
int miles;
double milesPG;
double dollarsPG;
printf("Input trip distance: ");
if (scanf("%d", &miles) != 1)
return 1;
printf("\nInput car miles per gallon: ");
if (scanf("%lf", &milesPG) != 1)
return 1;
printf("\nInput gas dollars per gallon: ");
if (scanf("%lf", &dollarsPG) != 1)
return 1;
double gasCost = (miles * (1.0 / milesPG) * dollarsPG);
printf("\nTotal trip cost is %.2f\n", gasCost);
return 0;
}
I am trying to create a C program which calculates the monthly payment and print a table of payment schedule for a fixed rate loan. My issue is that the loop only iterates once but I cannot figure out why. Here is how the output should looked like:
#include <stdio.h>
#include <math.h>
double calculatePayments(double loan, double rate, int payment);
int main(){
double loan,rate,monthly,principal,interest,balance;
int payment, counter;
counter = 0;
balance = 0.0;
printf("Enter amount of loan: ");
scanf("%lf", &loan);
printf("Enter interest rate per year:%% ");
scanf("%lf", &rate);
printf("Enter number of payments: ");
scanf("%d", &payment);
monthly = calculatePayments(loan, rate, payment);
printf("Monthly payment should be %.2f\n", monthly);
printf("—————AMORTIZATION SCHEDULE—————\n ");
printf("N\tPayment\tPrincipal\tInterest\tBalance\n ");
do{
rate = rate/12/100;
interest = loan * rate;
principal = monthly - interest;
balance = loan - principal;
counter++;
printf("%d\t%.2f\t%.2f\t\t%.2f\t\t%.2f\n", counter, monthly, principal, interest, balance);
}while(balance < 0);
return 0;
}
double calculatePayments(double loan, double rate, int payment) {
rate = rate/12/100;
double mul = pow(1+rate, payment);
return (loan * mul * rate) / (mul - 1);
}
Changing up the do ... while loop
// e.g. 7.5/12/100 = 0.00625
rate = rate/12/100;
do{
// e.g. 500*0.00625=3.125
interest = loan * rate;
// e.g. 101.88-3.125=98.76
principal = monthly - interest;
// e.g. 500-98.76=401.24
balance = loan - principal;
// update loan
loan = balance;
counter++;
printf("%d\t%.2f\t%.2f\t\t%.2f\t\t%.2f\n", counter, monthly, principal, interest, balance);
}while(balance > principal);
Balance would never be < 0. That is why you loop is only running once. If you had done a while loop instead of do while it wouldn't run at all.
Change balance < 0 to balance > 0
You are checking to loop only if balance is less than Zero.
but at the first iteration the value of balance would be 401$ (not < 0)
So breaking.
You should be checking for balance > 0 in while
I am writing a simple C program which takes data from user and does some maths. Here is my code:
#include <stdio.h>
int main(void) {
int semester_1,grade_1,grade_2,grade_3,subtotal,total_marks,average;
printf("Enter number of semester you to check");
scanf("%d", &semester_1);
while (semester_1 > 0) {
printf("Enter marks for first subject");
scanf("%d", &grade_1);
printf("Enter marks for second subject");
scanf("%d", &grade_2);
printf("Enter marks for third subject");
scanf("%d", &grade_3);
subtotal = grade_1 + grade_2 + grade_3;
total_marks = subtotal / 300 * 100;
printf("Your average this semester is %d", total_marks);
semester_1--;
}
average = semester_1 / 100 * total_marks;
printf("Your final average for all semesters is %d", average);
}
The problem with this code is that when I run the program returns 0 for final average for all semesters.
I wanted to get the final average for all semesters. Lets say if user enters 3 for numbers of semester they want to check and then they will be enter marks 3 times and then final average will be displayed, but it only gives 0.
#include <stdio.h>
int main(void) {
int semester_1,grade_1,grade_2,grade_3,subtotal,total_marks,average;
printf("Enter number of semester you to check");
scanf("%d", &semester_1);
while (semester_1 > 0) {
printf("Enter marks for first subject");
scanf("%d", &grade_1);
printf("Enter marks for second subject");
scanf("%d", &grade_2);
printf("Enter marks for third subject");
scanf("%d", &grade_3);
subtotal = grade_1 + grade_2 + grade_3;
total_marks = subtotal / 300.0 * 100.0;
printf("Your average this semester is %d", total_marks);
semester_1--;
}
average = semester_1 / 100.0 * total_marks;
printf("Your final average for all semesters is %d", average);
}
Rounding errors
It is probably because here:
total_marks = subtotal / 300 * 100;
subtotal is less than 300 * 100. And since both the operands of / are of type int, integer division is performed resulting in total_marks becoming 0.
Fix it by changing the type of total_marks to float, or more preferably, double. Then, cast one of the operands of / to float if you changed total_marks's type to float or double if you changed total_marks's type to double. The cast makes sure that integer division is not performed and floating-point division is performed.
You might need to do the same with average.
Fixed Code:
#include <stdio.h>
int main(void) {
int semester_1, grade_1, grade_2, grade_3, subtotal; /* Better to use an array */
double total_marks, average;
printf("Enter number of semester you to check");
scanf("%d", &semester_1);
while (semester_1 > 0) {
printf("Enter marks for first subject");
scanf("%d", &grade_1);
printf("Enter marks for second subject");
scanf("%d", &grade_2);
printf("Enter marks for third subject");
scanf("%d", &grade_3);
subtotal = grade_1 + grade_2 + grade_3;
total_marks = (double)subtotal / 300 * 100; /* Note the cast */
printf("Your average this semester is %f", total_marks); /* Note the change in the format specifier */
semester_1--;
}
average = (double)semester_1 / 100 * total_marks; /* Note the cast */
printf("Your final average for all semesters is %f", average); /* Note the change in the format specifier */
}
Your code has several issues. The first is the one pointed out by Cool Guy: dividing small integer by bigger integer will lead to the result being zero due to integer truncation.
The second is that you aren't keeping a running total, and you're decrementing the number of semesters for your loop counter.
You should add a new variable that stores the cumulative sum of each semester, and you should save the initial value of semester_1
(Also, style-wise,
for (int i = 0; i < num_semesters; i++)
is much more readable than (and preserves the value of num_semesters)
while(semester_1 > 0)
)
Good day! In a program I am writing for school we must make a cash register type program, seems simple enough, but for the life of me I can not get it to work. After taking in the number of products bought, then the price of all, the program must ask for the cash to pay, then give back the change. BUT the change must be given in amount of loonies back (or $1 bills), and then just the remaining cents. Help? I've gotten the loonies to work (somewhat) but I don't know how to do the change back.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int itemNum, justChange;
double prodPrice, tax, cashGiven, change, purchasePrice, changeGiven, changeBack, cashBack;
float totalPrice;
//Num of items
printf ("Number of items: ");
scanf("%d", &itemNum);
//Price of items
printf("Please enter price of items: ");
scanf("%lf", &prodPrice);
//Math Stuff
purchasePrice = itemNum*prodPrice;
tax = purchasePrice * 0.13;
totalPrice = purchasePrice*1.13;
//find change alone
//justChange = totalPrice
//Price Output
printf("Purchase price is: %.2lf \n",purchasePrice );
printf("TAX (HST 13%): %.2lf\n",tax );
printf("Total price is: %.2lf \n",totalPrice );
printf("Please Enter Cash: ");
scanf("%lf", &cashGiven);
printf("Please Enter Change: ");
scanf("%lf", &changeGiven);
//MAth stuuff again
double endCash;
double loony;
int yoloswag;
endCash = cashGiven - totalPrice;
loony = endCash/1;
loony = loony--;
if (loony<0)
printf ("Loonies: 0");
else
printf("Loonies: %.0lf \n",loony );
printf("change: %d ", totalPrice-floor(totalPrice) );
return 0;
}
Create an array with possible change values;
double cashValues[6] = {1, 0.5, 0.2, 0.1, 0.05, 0.01};
Then create a for loop in which you try to subtract the possible change values from the difference until the difference is zero.
double difference;
difference = cashGiven - totalPrice;
while (difference != 0) {
for(int i=0; i<6; i++) {
if(cashValues[i] <= difference) {
difference -= cashValues[i];
printf("%f \n", cashValues[i]);
i=0;
}
}
}
I am very much a beginner to programming in C so please help out here. I am trying to write a program that loops asking the user to enter a number, if the number is positive it adds it to the total, and if it is negative it ends the program and displays the average, lowest input, and highest input. Unfortunately no matter what I change with the low and high things I keep getting 'nan' for the low, and whatever the negative number for the high.. please help!
#include<stdio.h>
int main(void)
{
float input;
float total;
float low;
float high;
float average;
int count=0;
printf("\n\nPlease enter a positive number to continue or a negative number");
printf(" to stop: ");
scanf("%f", &input);
while (input > 0)
{
count = count + 1;
printf("\nPlease enter a positive number to continue or a negative");
printf(" number to stop: ");
scanf("%f", &input);
total = total + input;
if ( low < input )
{
( low = input );
}
else
{
( low = low );
}
}
if (input < high)
{
(high = input);
}
else
{
(high = high);
}
average = total / count;
printf("\n\n\nCount=%d",count);
printf("\n\n\nTotal=%f",total);
printf("\nThe average of all values entered is %f\n", average);
printf("\nThe low value entered: %f\n", low);
printf("\nThe highest value entered: %f\n", high);
return 0;
}
After compiling it with gcc and testing it with the numbers 1, 5, 4, then -1 I get the following output
Count=3
Total=8.000000
The average of all values entered is 2.666667
The low value entered: nan
The highest value entered: -1.000000
You have fallen victim to garbage values - a common mistake for beginners. Specifically, its happening in these lines -
float total;
float low;
float high;
float average;
When you write that, the system assigns the variables a memory location. The computer though, is not infinite, so it just uses a memory location that used to be used by something else, but is no longer being used. Most of the time though, the 'something else' doesnt clean up after itself (because it would take a lot of time), so the information that was there is left there, such as fdaba7e23f. This is totally meaningless to us, so we call it a garbage value.
You can fix this by initializing the variables, like so -
float total=0;
float low;
float high;
float average=0;
Note that you will have to add some extra logic for the low variable. Here is one way to do it -
printf("\n\nPlease enter a positive number to continue or a negative number");
printf(" to stop: ");
scanf("%f", &input);
low=input;
high=input;
while (input > 0)
....
....
As you can see, I just copied your code and added two lines after the first scanf.
For one thing, I don't know if you have noticed it, your count and total are all screwed up.
Please change the order of execution, apart from the initialization answer given by #Drgin
int total = input;
while (input > 0)
{
printf("\nPlease enter a positive number to continue or a negative");
printf(" number to stop: ");
scanf("%f", &input);
count = count + 1;
total = total + input;