Scanner not working(C code) - c

Here is my code:
#include <stdio.h>
float calculateBalance(float payment, float balance, float rate);
int main(void){
float loanAmount, interestRate, monthlyPayment;
printf("Enter amount of loan:");
scanf("%.2f", &loanAmount);
printf("\nEnter interest rate:");
scanf("%.1f", &interestRate);
printf("\nEnter monthly payment:");
scanf("%.2f", &monthlyPayment);
loanAmount = calculateBalance(monthlyPayment, loanAmount, interestRate);
printf("Balance remaining after first payment: %.2f\n", loanAmount);
loanAmount = calculateBalance(monthlyPayment, loanAmount, interestRate);
printf("Balance remaining after second payment: %.2f\n", loanAmount);
loanAmount = calculateBalance(monthlyPayment, loanAmount, interestRate);
printf("Balance remaining after third payment: %.2f\n", loanAmount);
}
float calculateBalance(float payment, float balance, float rate){
return (balance-payment + balance*rate);
}
I am trying to calculate the balance after three payments are made; However, when I try and run the code in terminal, it's not letting me input anything, and instead is just reading in random numbers and then calculating the balance after three payments(I want to be able to input things, but it isn't allowing me to). How do I fix this?

The issue is in the fmt string itself. As #T.C. said in a comment
try using
scanf("%f", &var);
instead. If there are only 2 dec values, then it will only read that.

You can try a adding a getc(stdin); after each scanf.

Related

C doesn't show code after entering it in console

I am currently doing college task to create a simple program using C, to enter and display prices of shirts in store. The problem is about that it doesn't show prices after I enter them in console. I don't really understand what is the problem, because my experience in coding on C ~1 week. Can anyone help with that? Thanks.
int main(void)
{
float small = 0.0;
float medium = 0.0;
float large = 0.0;
float total = 0.0;
printf("Set Shirt Prices\n");
printf("================\n");
printf("Enter the price for a SMALL shirt: $");
scanf("%f", &small);
printf("Enter the price for a MEDIUM shirt: $");
scanf("%f", &medium);
printf("Enter the price for a LARGE shirt: $");
scanf("%f\n", &large);
printf("Shirt Store Price List\n");
printf("======================\n");
printf("SMALL : $%f\n", small);
printf("MEDIUM : $%f\n", medium);
printf("LARGE : $%f\n", large);
return 0;
}
This line is problematic:
scanf("%f\n", &large);
It's expecting the user to type a float followed by additional text.
Change it to:
scanf("%f", &large);
And if want the end-of-line character, you can prepend it to the next statement.
printf("\nShirt Store Price List\n");

Two scanf functions but one reads a different value

I'm struggling in letting the program read the variable total that was previously input after asking for the input for the variable month. The total is always 28257 and I don't know why.
I found out using " %c" on line 11 works, but I would like to know why "%s" doesn't.
#include <stdio.h>
int main(void) {
int total;
char month;
float sales;
printf ("Enter total amount collected (-1 to quit): ");
scanf("%d", &total);
printf("Enter name of month: ");
scanf("%s", &month);
printf("total collections : $ %d\n", total);
sales = (total/1.09);
printf("sales : $ %.2f\n", sales);
printf("county sales tax: $ %.2f\n", sales * 0.05);
printf("state tax: $ %.2f\n", sales*0.04);
printf("total sales tax collected: $ %.2f\n", sales *0.05 + sales *0.04);
return 0; }
you declared month as character, so you should use %c for input. %s is used for input character array. and before scanf("%c", &month);, also use getchar();.
getchar();
scanf("%c", &month);

How To Use Decimals Of An Integer

I would like overpay to display overpay as the total amount paid if the result was not rounded. calculateMonths must be an integer which makes this much more difficult. I tried using
double dblCalculateMonths = (double)calculateMonths(principal, annualInterestRate, monthlyPayment);
but it did not work properly. I am not sure how to fix this problem while keeping calculateMonths as an integer. Help would be very much appreciated!
I would like the results to look like this:
** Welcome to the CPSC 1010-S3 Payment Calculator **
Enter the principal amount: 5000.00
Enter the annual interest rate (in %): 15.0
Enter the monthly payment: 100.00
Calculating...
Total # of months needed to pay off: 79
App roximate # of years needed to pay off: 6.6
Total interest paid: $2900.00
Total amount paid: $7900.00
You overpaid: $4.43
But the last line displays as
You overpaid: $100.00
I am not sure how to change this. My list of code is below
#include <stdio.h>
#include <math.h>
int calculateMonths(double principal,double annualInterestRate,double monthlyPayment)
{
double x = ((log(monthlyPayment)-log(monthlyPayment-annualInterestRate/1200.0*principal))/log(annualInterestRate/1200.0+1.0));
return x;
}
int main()
{
double principal, annualInterestRate, monthlyPayment;
printf("** Welcome to the Payment Calculator **\n\n");
printf("Enter the principal amount:\t\t\t");
scanf("%lf", &principal);
printf("Enter the annual interest rate (in%%):\t\t");
scanf("%lf", &annualInterestRate);
printf("Enter the monthly payment:\t\t\t");
scanf("%lf", &monthlyPayment);
printf("\nCalculating...\n\n");
double roundedMonths = calculateMonths(principal, annualInterestRate, monthlyPayment)+1;
printf("Total # of months needed to pay off:\t\t %.0f\n", roundedMonths);
double years = roundedMonths/12;
printf("Approcimate # of years needed to pay off: \t %.1f\n", years);
double amountPaid = roundedMonths * monthlyPayment;
double interestPaid = amountPaid-principal;
printf("Total interest paid:\t\t\t\t $%.2f\n", interestPaid);
printf("Total amount paid:\t\t\t\t $%.2f\n", amountPaid);
double dblCalculateMonths = (double)calculateMonths(principal, annualInterestRate, monthlyPayment);
double overpay = amountPaid - dblCalculateMonths*monthlyPayment;
printf("You overpaid:\t\t\t\t $%.2f\n", overpay);
printf("%f", dblCalculateMonths);
printf("\n\n");
return(0);
}
what's the logic in keeping calculateMonths() an integer? make it a double and it should work.
double calculateMonths(double principal,double annualInterestRate,double monthlyPayment)
and make roundedMonths an integer. Also you could add 0.5 to have the right round.
int roundedMonths = calculateMonths(principal, annualInterestRate, monthlyPayment)+0.5;
printf("Total # of months needed to pay off:\t\t %d\n", roundedMonths);
LE: Try this:
int calculateMonths(double principal,double annualInterestRate,double monthlyPayment, double *dblCalculateMonths)
{
*dblCalculateMonths = ((log(monthlyPayment)-log(monthlyPayment-annualInterestRate/1200.0*principal))/log(annualInterestRate/1200.0+1.0));
return *dblCalculateMonths;
}
int main()
{
double principal, annualInterestRate, monthlyPayment, dblCalculateMonths;
printf("** Welcome to the Payment Calculator **\n\n");
printf("Enter the principal amount:\t\t\t");
scanf("%lf", &principal);
printf("Enter the annual interest rate (in%%):\t\t");
scanf("%lf", &annualInterestRate);
printf("Enter the monthly payment:\t\t\t");
scanf("%lf", &monthlyPayment);
printf("\nCalculating...\n\n");
double roundedMonths = calculateMonths(principal, annualInterestRate, monthlyPayment, &dblCalculateMonths)+1;
printf("Total # of months needed to pay off:\t\t %.0f\n", roundedMonths);
double years = roundedMonths/12;
printf("Approcimate # of years needed to pay off: \t %.1f\n", years);
double amountPaid = roundedMonths * monthlyPayment;
double interestPaid = amountPaid-principal;
printf("Total interest paid:\t\t\t\t $%.2f\n", interestPaid);
printf("Total amount paid:\t\t\t\t $%.2f\n", amountPaid);
double overpay = amountPaid - dblCalculateMonths*monthlyPayment;
printf("You overpaid:\t\t\t\t $%.2f\n", overpay);
printf("%f", dblCalculateMonths);
printf("\n\n");
return(0);
}

Yes/No Prompt To Rerun Program

I would like my program to have a yes no prompt to ask if the program should be run again. Right now, it skips the user input completely. How can I do this effectively?
Any help would be appreciated. Thank you!
#include <stdio.h>
#include <math.h>
double Months(double principal,double annualInterestRate,double monthlyPayment)
{
double x = ((log(monthlyPayment)-log(monthlyPayment-annualInterestRate/1200.0*principal))/log(annualInterestRate/1200.0+1.0));
return x;
}
int calculateMonths(double y)
{
double principal, annualInterestRate, monthlyPayment;
y = Months(principal, annualInterestRate, monthlyPayment);
return y;
}
int main()
{
double principal, annualInterestRate, monthlyPayment;
char response = 'Y';
printf("** Welcome to the CPSC 1010-S3 Payment Calculator **\n\n");
do{
printf("Enter the principal amount:\t\t\t");
scanf("%lf", &principal);
printf("Enter the annual interest rate (in%%):\t\t");
scanf("%lf", &annualInterestRate);
printf("Enter the monthly payment:\t\t\t");
scanf("%lf", &monthlyPayment);
printf("\nCalculating...\n\n");
int roundedMonths = Months(principal, annualInterestRate, monthlyPayment)+.5;
printf("Total # of months needed to pay off:\t\t %d\n", roundedMonths);
double years = Months(principal, annualInterestRate, monthlyPayment)/12;
printf("Approcimate # of years needed to pay off: \t %.1f\n", years);
double amountPaid = roundedMonths * monthlyPayment;
double interestPaid = amountPaid-principal;
printf("Total interest paid:\t\t\t\t $%.2f\n", interestPaid);
printf("Total amount paid:\t\t\t\t $%.2f\n", amountPaid);
double overpay = amountPaid - Months(principal, annualInterestRate, monthlyPayment)*monthlyPayment;
printf("You overpaid:\t\t\t\t $%.2f\n", overpay);
int extraMonthlyPayment = monthlyPayment*.1;
int monthsEarly = ((log((monthlyPayment*1.1))-log((monthlyPayment*1.1)-annualInterestRate/1200.0*principal))/log(annualInterestRate/1200.0+1.0));
int newMonths = Months(principal, annualInterestRate, monthlyPayment)-monthsEarly;
printf("Did you know if you paid an additional $%d per month, you would pay off your loan %d months earlier?\n\n", extraMonthlyPayment, newMonths);
printf("Do you wish to calculate another payoff? (Y/N):\t");
scanf("%c", &response);
}
while(response == 'Y' || response == 'y');
printf("Thank you for using the Payment Calculator!\n\n");
return(0);
}
Using scanf is suboptimal.
I'd add a
while (getchar());
line before the last scanf.
Please make sure you don't miss or mangle other data due to the newlines in the input buffer.

how to compare user input to a string for a while loop in c programming

We are trying to execute the if statements based on what the user inputs. For example if the user input Yen then we want the if statement to be executed and the conversion to yen be calculated.
After the user has input how many gallons of gas the calculations are made and we are left with a total cost. We want to then let the user choose a currency that they would like to convert the total cost into. We have given the user three choices. If the user inputs something that is not any of the given choices then the user is allowed to re-enter a choice again. One the user does enter one of the 3 choices then we want the currency conversion to be executed.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <string.h>
#include <stdbool.h>
float gas_gallons;
float cost_today_gallons;
int main()
{
char input;
printf("Please enter the number of gallons of gasoline: ");
scanf("%c", &input);
while (!isdigit(input))
{
printf("\nYou need to enter a digit. Please enter the number of gallons of gasoline: ");
scanf("%c", &input);
}
if (isdigit(input))
{
printf("\nThe users input was %c", input);
gas_gallons = input - '0';
printf("\nAs a float it is now %f", gas_gallons);
float carbon_dioxide_pounds = gas_gallons * 19.64;
printf("\n%.2f gallons of gasoline produces approximately %f pounds of carbon dioxide.", gas_gallons, carbon_dioxide_pounds );
float barrels_crude_oil = gas_gallons/19.0;
printf("\n%.2f gallons of gasoline requires %f barrels of crude oil.", gas_gallons, barrels_crude_oil);
cost_today_gallons = gas_gallons*2.738;
printf("\n%.2f gallons of gasoline costs a total average of %f US dollars today.", gas_gallons, cost_today_gallons);
}
char currency[100];
printf("\nChoose a currency you want to see your total cost in (Euro, Pound, or Yen): ");
scanf("%c", &currency);
printf("\nThe currency chosen is %c", currency);
char Yen[100];
char Euro[100];
char Pound[100];
while (strcmp(currency, Yen) != 0 || strcmp(currency, Euro) != 0 || strcmp(currency, Pound) != 0)
{
printf("\nYou need choose one of these currencies (Euro, Pound or Yen). Please enter one: ");
scanf("%s", &currency);
}
if (strcmp(currency, Yen) == 1)
{
float yen_total_cost = cost_today_gallons*123.07;
printf("\n%.2f gallons of gasoline costs a total average of %f US dollars today.", gas_gallons, yen_total_cost);
}
if (strcmp(currency, Euro) == 1)
{
float euro_total_cost = cost_today_gallons*0.92;
printf("\n%.2f gallons of gasoline costs a total average of %f US dollars today.", gas_gallons, euro_total_cost);
}
if (strcmp(currency, Pound) == 1)
{
float pound_total_cost = cost_today_gallons*0.65;
printf("\n%.2f gallons of gasoline costs a total average of %f US dollars today.", gas_gallons, pound_total_cost);
}
return 0;
}
Some problems I can see in your code:
You should use scanf("%s", str) to read a string, see scanf()
Also, strcmp() returns 0 when its parameters are equal.
And char[] Yen, Euro, Pound in your code are not initialized.

Resources