to calculate remaining loan balance - c

I am trying to write a program in C to calculate the remaining balance after 1st, 2nd & 3rd monthly payments, given the loan, monthly payment amount, and interest rate. I am having a problem in entering the input (floating point numbers) i.e it only takes one input (loan) & displays the answer without considering the other 2 inputs (interest rate & monthly payments).
This problem occurs only when I use the floating-point numbers (even in other programs also). I want to ask if this is due to coding or due to any other reason.
My code is as follows:
#include<stdio.h>
main()
{
float loan,interest,monthly_payment;
float balance_Imonth,balance_IImonth,balance_IIImonth;
printf("Enter the amount of loan: ");
scanf("%.2f",&loan);
printf("Enter the amount of interest: ");
scanf("%.2f",&interest);
printf("Enter the amount of monthly payment: ");
scanf("%.2f",&monthly_payment);
balance_Imonth=((interest/(100*12))*loan)+(loan)-(monthly_payment);
balance_IImonth=((interest/(100*12))*loan)+(balance_Imonth)- (monthly_payment);
balance_IIImonth=((interest/(100*12))*loan)+(balance_IImonth)-(monthly_payment);
printf("Balance remaining after I payment: $%.2f\n",balance_Imonth);
printf("Balance remaining after II payment: $%.2f\n",balance_IImonth);
printf("Balance remaining after III payment: $%.2f\n",balance_IIImonth);
}

The format specification "%.2f" is OK for printf but not for scanf. Use just "%f".
In your program, all the scanf function calls fail. You are just seeing undefined behavior due to use of uninitialized variables.
Always check the return value of scanf to make sure that the operation succeeded before you proceed to use the variables in which scanf stores the results.
Use
if ( scanf("%f", &loan) != 1 )
{
// Deal with error.
}

Related

Having difficulty correctly inputting multiple integers at the same time using scanf()

So I have a coding project where I have to calculate the overall grade of a student in a class where they have 4 quizzes, 2 midterms, and 1 final exam. The quiz and exam are weighted 30% and the midterm 40%. I just help with 2 things:
My code doesn't want to start w/o having 4 individual input numbers (79 80 0 0).
When getting to the exam part of the code, it for some reason bypasses the needed user input and autos it to the 3rd number in the quiz coding.
I'm coding in c programming.
#include <stdio.h>
int main()
{
int testOne, testTwo;
float totTest, percTest, testPoint;
printf("Enter you test grades:\n");
scanf("%d%d\n",&testOne,&testTwo);
totTest=testOne+testTwo;
printf("Your total grade points is: %.1f\n", totTest);
testPoint=200;
percTest=(totTest*.40)/testPoint *100;
printf("Your percentage is %.1f%\n", percTest);
int quizOne, quizTwo, quizThree, quizFour;
float totQuiz, percQuiz, quizPoint;
printf("Enter you quiz grades:\n");
scanf("%d%d%d%d\n", &quizOne, &quizTwo, &quizThree, &quizFour);
totQuiz=quizOne+quizTwo+quizThree+quizFour;
printf("Your total quiz grade is %.1f\n", totQuiz);
quizPoint=400;
percQuiz=(totQuiz*.30)/quizPoint *100;
printf("Your quiz percentage is %.1f%\n", percQuiz);
int examOne, examPoint; <This is the code that automatically messes up>
float percExam, finGrade;
printf("Enter your exam grade\n");
scanf(" %d\n", &examOne);
examPoint=100;
percExam=(examOne*.30)/examPoint *100;
printf("Your final exam grade is %.1f\n", percExam);
finGrade=(percExam+percQuiz+percTest);
printf("Your overall grade is %.1f%\n", finGrade);
return 0;
}
Your problems have nothing to do with the logic of your program, nothing to do with computing grades, and everything to do with: scanf. scanf is simultaneously the most useful-looking, and the most actually useless, function in the C library when it comes to introductory C programming.
Here are three simple rules for using scanf in introductory C programming:
Use only one of the following four input formats: "%d", "%s", "%f", "%lf". If you simply must read individual characters, you can add a fifth: " %c" (but make sure you always use that extra space). Use these in isolation, one at a time, without combining them or adding any other characters.
Always check the return value of scanf. If it does not return 1, print an error message and exit: if(scanf(...) != 1) {printf("input error!\n"); exit(1); }
If you want to do something fancier, that you can't accomplish with the limited number of formats allowed by rule 1, then it's time to learn how to use something better than scanf.
In particular, don't try to read multiple numbers at once using formats like %d%d. And don't use \n in scanf format statements, either — it doesn't do what you think, and it's probably causing you problems.

scanf doesn't read double

I got problems regarding the minus operation in c.
printf("\nPlease enter your payment:\n", userpayment);
scanf("%.2f", &userpayment);
customerchange = userpayment - totalfinal;
printf("The amount of change is %.2f\n", customerchange);
I declared userpayment and totalfinal as double.
Whenever I input the price for example; userpayment = 2000 and the totalfinal is 1500, the output will always be 1500.
What is the solution to this?
This is the output:
Enter the Price of Item:
500
Enter Quantity of Item:
3
The total amount of Payment is: RM1500.00
Is this the last item?
y
Rm50 cash rebate has been given to the customer.
Total Payment before cash rebate is: 1500
Total Payment after cash rebate is 1450
Please enter your payment:
5000
Your change is RM-14500.00
If "userpayment" is defined as a double, then change
scanf("%.2f", &userpayment);
to
scanf("%lf", &userpayment);
or change your variables to floats instead.
As it stands, you're scanning a float into the memory of a double, resulting in unpredictable behavior.
You have an incorrect format specifier in scanf. Read the documentation.
http://www.cplusplus.com/reference/cstdio/scanf/
You should also check the return value of scanf to ensure that it was able to parse what you expected it to parse.
Also, if you had read your compiler warnings you could have saved yourself the trouble of asking this question.
You are confusing the format from printf, it is similar but not the same, try just replacing %.2f to %lf
Since you defined your variable as double you should use:
scanf("%lf", &userpayment);
The f is for float values, lf (long float) for doubles.

Simple C program not calculating correctly

So, I'm completely new to programming, and I'm learning to program C. I'm trying to write a simple program in C to calculate commission as follows
#include<stdio.h>
int main()
{
float fRate, fSales_Price, fCost, fCommission;
printf("\nEnter your commission rate: ");
scanf("%.2f",&fRate);
printf("\nEnter the price of the item sold: ");
scanf("%.2f", &fSales_Price);
printf("\nEnter the original cost of the item: ");
scanf("%.2f", &fCost);
fCommission = (fRate / 100) * (fSales_Price - fCost);
printf("\nYour commission is: %.2f", fCommission);
}
Whenever I try to run it, two things happen. First, if I try to enter any decimals into the program, e.g. if I said the rate was 12.5, it immediately skips the other inputs and completes the program, saying commission is 0.00. If I ignore decimals, the program runs fine until the end, when I still get commission as 0.00. Any suggestions?
Your format specifier is wrong, you must use compiler warnings if you do, then you wouldn't be asking this, because that format specifier is invalid, you cannot limit the number of decimal places with scanf() it's been discussed in many questions on SO, more importantly you don't need to, and it wouldn't be meaningful, so just remove the .2 from your format specifier, and instead, check that scanf() succeeded before using the values.
"%.2f" is an illegal format string for scanf, so your code causes undefined behaviour. The correct format string is "%f".
Also you should check the result of scanf. If scanf fails, the bad data is not consumed from the input and so subsequent scanfs fail too (this is why you see the other inputs skipped).
For example:
if ( 1 != scanf("%f", &fRate) )
{
printf("Invalid input for fRate.\n");
exit(EXIT_FAILURE);
}
"%.2f" is not a valid format for scanf. See scanf() manual page for details.
The easiest format to use is "%f".
Also, it's a good practice to check the return value of scanf so you know when the operation was successful.
if ( scanf("%f", &fRate) != 1 )
{
// Error reading the data.
// Deal with the error.
}

C - scanf gets skipped over (even with " %d")

I am trying to figure out why I can't get this to run properly. I just want four inputs from the user, and run the calculation at the end.
#include <stdio.h>
#include <math.h>
int main(){
double amount; /* amount on deposit */
double principal; /* what's the principal */
double rate; /* annual interest rate */
int year; /* year placeholder and no. of total years */
int yearNo;
printf("What is the principal? ");
scanf("%d", &principal);
printf("What is the rate (in decimal)? ");
scanf(" .2%d", &rate);
printf("What is the principal? ");
scanf(" %d", &principal);
printf("How many years? ");
scanf(" %d\n", yearNo);
printf("%4s%21s\n", "Year", "Amount on deposit");
/* calculate the amount on deposit for each of ten years */
for (year = 1; year <= yearNo; year++){
amount = principal * pow(1.0 + rate, year);
printf("%4d%21.2f\n", year, amount);
}
return 0;
}
It properly asks for the principal and rate, but then skips over the question about Principal and asks for years. Then it just sits there waiting for a "ghost" entry?
I've been reading that the scanf() adds some whitespace when hitting enter but thought the space before the %d would fix that?
I also saw you could add do { c=getchar(); } while ( c != '\n'); after each scanf but that seems to crash the program (I added int c = 0; to the beginning too).
Thanks for any help or ideas!
EDIT:
When I change the erroneous format specifier from:
scanf(" .2%d", &rate);
to:
scanf(" %d", &rate);
I then get a crash after entering my values.
.2%d is not a valid format string.
For a start, the % has to come first. In addition, if you're after a floating point value, d is not the right character - it's for integral values.
You should be using something like %f (you don't need width or precision modifiers).
On top of that, you've made a minor mistake of not using a pointer for one of your scanf calls:
scanf(" %d\n", yearNo);
That's probably going to cause a crash, and should be changed to:
scanf(" %d\n", &yearNo);
And, as a final suggestion, it's totally unnecessary to use whitespace before (or a newline after) %d or %f family of format specifiers. The scanner automatically skips whitespace before both of those.
So, the only two scanf format strings you need in this program are "%d" and "%lf" (f is for floats, lf is for doubles).

Issues with program validation. Please help!

//Guys I have issues with my code and have been tearing my hair apart trying to resolve this. THe issue is that I am trying to validate my code so it doesn't calculate for negative numbers. If any one can help smooth up this program I would really appreciate it. Please.
//The objective of the tax calculator program will be to use C programming to calcualte sales tax for each of the Kudler Fine Food stores (DelMar, Encinitas and La Jolla)
//Standard input/output processing
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
//Starting point
int main ()
{
//Variables defined
//st = sales tax, tax rated = tr, pa = total purchase amount, sa = purchase amoount
float fstDelmar;
float ftrDelmar;
float fpaDelmar;
float fstEncinitas;
float ftrEncinitas;
float fpaEncinitas;
float fstLajolla;
float ftrLajolla;
float fpaLajolla;
float fsaPurchaseAmount;
int fStoreselect;
//Variable initializations for tax rates and purchase amount
ftrDelmar = .0725;
ftrEncinitas = .075;
ftrLajolla = .0775;
fsaPurchaseAmount = 0;
//Header & Introduction
printf("\n***********************************************************************");
printf("\n* Kudler Fine Foods *");
printf("\n* Sales Tax Calculator *");
printf("\n* Version 3.0 *");
printf("\n***********************************************************************\n");
//Ask user to select store.
printf ("\n STORE LOCATION \n");
printf ("\n 1) Del Mar \n");
printf ("\n 2) Encinitas \n");
printf ("\n 3) La Jolla \n");
printf ("\n Please select the store location (1-3): \n");
scanf ("%d", &fStoreselect);
//Validate store selection.
while (fStoreselect < 1 || fStoreselect > 3) {
fflush (fStoreselect);
printf ("INVALID SELECTION! Please select a valid location (1-3): \n");
scanf ("%d", &fStoreselect);
}
//Ask user to enter in total purchase amount.
printf ("\n What was your purchase amount? ");
scanf("$%f", &fsaPurchaseAmount); //user enters variable amount
//Validation to ensure that user's enter in purchase amounts using correct format.
while (fsaPurchaseAmount <= 0.0)
{
fflush(fsaPurchaseAmount);
printf("\n INVALID SELECTION! Please enter a valid purchase amount greater than zero.\n");
printf("\n The purchase amount is: $ ");
scanf("%f", &fsaPurchaseAmount);
}
//Calculation of sales tax in dollars for each of the store locations
fstDelmar = fsaPurchaseAmount * ftrDelmar;
fstEncinitas = fsaPurchaseAmount * ftrEncinitas;
fstLajolla = fsaPurchaseAmount * ftrLajolla;
//Calculation of total sales amount for each of the locations
fpaDelmar = fsaPurchaseAmount + fstDelmar;
fpaEncinitas = fsaPurchaseAmount + fstEncinitas;
fpaLajolla = fsaPurchaseAmount + fstLajolla;
//Displaying sales amount for purchase for each of the different locations
switch (fStoreselect) {
case 1:
//for Delmar location
printf("\n Purchase Amount Sales Tax Total Sales Amount ");
printf("\n _______________ _________ _________________ ");
printf("\n $%.2f $%.2f $%.2f",fsaPurchaseAmount, fstDelmar, fpaDelmar);
break;
case 2:
//for Encinitas location
printf("\n Purchase Amount Sales Tax Total Sales Amount ");
printf("\n _______________ _________ _________________ ");
printf("\n $%.2f $%.2f $%.2f",fsaPurchaseAmount, fstEncinitas, fpaEncinitas);
break;
case 3:
//for La Jolla location
printf("\n Purchase Amount Sales Tax Total Sales Amount ");
printf("\n _______________ _________ _________________ ");
printf("\n $%.2f $%.2f $%.2f",fsaPurchaseAmount, fstLajolla, fpaLajolla);
break;
}
printf("\n Hit the ENTER key to exit program\n");
//Pause the screen and wait for user to hit the ENTER key
getchar();
//EOF
}
This line has bug:
scanf("$%f", &fsaPurchaseAmount); //user enters variable amount
it supposed to be:
scanf("%f", &fsaPurchaseAmount); //user enters variable amount
Here are some observation about the code as presented:
Don't use floating point for money. It will only cause grief later. Ideally, take advice from an accounting professional. In the mean time, do arithmetic in cents, and scale to and from dollars for display.
Calculations like sales tax might be correctly done with a floating point multiply, but make sure you comply with the accepted practices for rounding back to whole cents. Again, seek advice from an accounting professional.
fflush() doesn't do what you think it does. For a file descriptor opened for writing (such as stdout) it guarantees that all output on that descriptor has been completed. It is used after printing a prompt and before calling something like scanf() to read the input. An example is: printf("What is your favorite color? "); fflush(stdout); fgets(color, sizeof(color), stdin);
Always check the return value of scanf(). It returns the number of conversions that succeeded. If it doesn't match the number of format specifiers, then only those that succeeded had values written to the named variables.
Be wary of literal characters other than whitespace appearing in a scanf() format string. These must be matched exactly by the input text, or the conversion fails. So a format like "$%f" is only matched by input that includes a literal dollar sign. This is probably not what your user expects. The format "%f" is easier on the user. If you want to allow an optional dollar sign, then scanf() may not be the best choice.

Resources