Yes/No Prompt To Rerun Program - c

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.

Related

C language: When I use scanf the output console displays "Program ended with exit code: 0[whatever I input for scanf]" How do I fix this?

For example:
printf("Please enter the amount of money you want to accumulate: ");
scanf("%f", &cashGoal);
printf("You would like to save up to $%.2f\n", cashGoal);
Returns this:
Please enter the amount of money you want to accumulate: Program ended with exit code: 0123123
You would like to save up to $123123.00
Edit: Here's the full code, it's my homework project so it's a little long
#include <stdio.h>
#include <math.h>
FILE *fp;
#define PENNY 0.01
int daystoCashGoal(float);
int main(void) {
fp = fopen("csis.txt", "w");
float cashGoal;
printf("Please enter the amount of money you want to accumulate: ");
fprintf(fp, "Please enter the amount of money you want to accumulate: ");
scanf("%f", &cashGoal);
printf("\n");
fprintf(fp,"\n");
printf("You would like to accumulate $%.2f.\n\n", cashGoal);
fprintf(fp, "You would like to accumulate $%.2f.\n\n", cashGoal);
daystoCashGoal(cashGoal);
fclose(fp);
return 0;
}
//Calculates the number of days it will take to accumulate the user-desired amount, doubles the deposit for each day, and sums up the balance for each day
int daystoCashGoal(float cashGoal){
int day = 1;
float dailyBalance = 0, dailyDeposit;
printf("DAY DEPOSIT BALANCE\n");
fprintf(fp, "DAY DEPOSIT BALANCE\n");
printf("___ _______ _______\n");
fprintf(fp, "___ _______ _______\n");
while (dailyBalance <= cashGoal) {
dailyDeposit = (pow( 2, day - 1)) * PENNY;
dailyBalance += dailyDeposit;
printf("%3d %5s %10.2f %5s %10.2f\n", day,"", dailyDeposit,"", dailyBalance);
fprintf(fp, "%3d %5s %10.2f %5s %10.2f\n", day,"", dailyDeposit,"", dailyBalance);
if (dailyBalance <= cashGoal) {
day ++;
}
else if (dailyBalance >= cashGoal) {
continue;
}
}
if (dailyBalance >= cashGoal) {
printf("\nIt took %d days to accumulate at least $%.2f.\n", day, cashGoal);
fprintf(fp, "\nIt took %d days to accumulate at least $%.2f.\n", day, cashGoal);
}
return day;
}
I'm not looking for advice on the rest of my code since this project has already been graded, but the exit code issue is affecting the rest of my projects and I'm not sure what I'm doing wrong. Thanks

How to make the a code repeat itself while changing the month date in C?

I have done this code and I have made a loop where my code will restart from scratch however I want the program to restart while changing the month date and also asking the user how many months they would like so the program will run a certain amount of times, as I have added the month 1 being the first month.
#include<stdio.h>
#include<stdlib.h>
float twag(float amount,float rate)
{
float si;
si = (amount * rate) / 100;
return si;
}
float twag2(float amount,float rate)
{
float er;
er = twag(amount, rate) + amount;
return er;
}
int main()
{
char answer;
do {
float amount;
float rate;
float si;
float er;
printf("Month1\n");
printf("\nEnter intial deposit : ");
scanf("%f", &amount);
printf("\nEnter Rate of Interest : ");
scanf("%f", &rate);
printf("\nSimple Interest : %.2f \n", twag(amount,rate));
printf("\nEnd Payment: %.2f \n",twag2(amount,rate));
if (amount <= 100)
printf("interest rate should be 10%%\n");
else if (amount <= 200)
printf("interest rate should be 50%%\n");
else if (amount <= 500)
printf("interest rate should be 80%%\n");
else if (amount >= 500)
printf("interest rate should be 90%%\n");
system("PAUSE");
printf("\nPress Y to continue to the second month or Press any Key To
Exit");
scanf(" %c", &answer); //
}
while (answer == 'y' || answer == 'Y');
return 0;
}
Assuming you're applying monthly interest, you at least need to keep record of the current month and year, starting at today's date, so the way to do that is by using localtime
void get_date(int *month, int *day, int *year)
{
struct tm *current;
time_t timenow;
time(&timenow);
current = localtime(&timenow);
*month = current->tm_mon+1;
*day = current->tm_mday;
*year = current->tm_year+1900;
}
I suggest you read here on why system("PAUSE") is bad, besides that, You defined your loop variables inside the loop, which means they're going to reset each time you loop, and your interest should be constant during the loop, so your code should look like this
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
float twag(float amount,float rate);
float twag2(float amount,float rate);
void get_date(int *month, int *day, int *year);
int main()
{
char answer;
float amount, rate, si, er;
int day, month, year;
printf("\nEnter intial deposit : ");
scanf("%f", &amount);
printf("\nEnter Rate of Interest : ");
scanf("%f", &rate);
get_date(&month, &day, &year);
do
{
// increment date by 1 month
if (++month > 12) month=1, year++;
printf("\nDate %d/%d/%d \n", day,month,year);
printf("\nSimple Interest : %.2f \n", twag(amount,rate));
printf("\nEnd Payment: %.2f \n",twag2(amount,rate));
amount = twag2(amount,rate);
printf("\nPress Y to continue to the next month or Press any Key To Exit");
scanf("%c", &answer);
}
while (answer == 'y' || answer == 'Y');
return 0;
}

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);
}

Loop with rolling total in c

I am trying to get a c program to ask me how many items i am buying than to ask the price for each item while keeping a rolling total and than ask again in a loop. I have the loop working fine but am having problems getting it to give me proper output.
here is the output i am getting when i run it.
http://i119.photobucket.com/albums/o134/halodude808/assignment2_zpsd46e84b8.jpg
#include <stdio.h>
#include <math.h>
int main(void)
{
//variables used
float penny = .01;
float nickel = .05;
float dime = .1;
float quarter = .25;
int items = 0;
float paid= 0.0;
float total = 0.0;
float price =0.0;
int counter =0.0;
for (;;)
{
printf("Please enter the number of grocery items:");
scanf("%d", &items);
for (counter = 1; counter <= items; counter++)
{
printf("Please enter the price for item #%d:", counter);
scanf("%f", &price);
total += price;
}
printf("items = %d total = %f \n", &items, &total);
getchar();
getchar();
}
}
Change
printf("items = %f total = %f \n", &items, &total);
to
printf("items = %i total = %f \n", items, total);
Also, you might want to consider checking for invalid values (zeroes, negative, characters, etc).

Scanner not working(C code)

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.

Resources