I am working on a program in C that can return loan payment.
yearInt is year interest
loanAmt is total amount of loan
monthlyPay is monthly payment
numberPay is number of monthly payment
For some reasons, when I run the program, there is nothing shows up, even I type in a negative number.
Is there anyway to fix it?
#include <stdio.h>
int main(void)
{
float yearInt = -1;
int loanAmt = -1;
float monthlyPay = -1;
int numberPay = -1;
int count = 0;
while (loanAmt<0)
{
printf("Please enter valid loan value: \n");
scanf("%f", &loanAmt);
}
while (yearInt<0)
{
printf("Please enter valid yearly interest value: \n");
scanf("%f", &yearInt)
}
while (monthlyPay<0)
{
printf("Please enter valid monthly payment value: \n");
scanf("%f", &monthlyPay);
}
while (numberPay<0)
{
printf("Please enter valid number of monthly payments: \n");
scanf("%f", &numberPay);
}
if(loanAmt>monthlyPay)
{
while(count<numberPay)
{
loanAmt = loanAmt*(1 + (yearInt/12)) - monthlyPay;
count += count+1;
}
printf("The amount of last payment is: %.2f\n", loanAmt);
else
printf("The amount of last payment is: %.2f\n", loanAmt);
}
return 0;
}
You are using the wrong format specifier to read loanAmount and numberPay. Instead of "%f", use "%d".
scanf("%d", &loanAmt);
and
scanf("%d", &numberPay);
Also, always check the return value of scanf to make sure that it was able to assign data to all the variables.
Change the loop:
while (loanAmt<0)
{
printf("Please enter valid loan value: \n");
scanf("%d", &loanAmt);
}
to
while (loanAmt<0)
{
printf("Please enter valid loan value: \n");
if ( scanf("%d", &loanAmt) != 1 )
{
// Discard the rest of the line.
int c;
while ( (c = fgetc(stdin)) = '\n' && c != EOF );
}
}
It will be still better to put all the checks in a function and call the function from main.
int readInt(char const* prompt)
{
int val = -1;
printf("%s\n", prompt);
while ( scanf("%f", &val) != 1 || val < 0)
{
// Discard rest of the line.
int c;
while ( (c = fgetc(stdin)) = '\n' && c != EOF );
// If EOF is reached, we have a problem.
if ( c == EOF )
{
exit(0);
}
printf("%s\n", prompt);
}
return val;
}
and then, use:
loanAmount = readInt("Please enter valid loan value: ");
Add a similar function to read floats and call it for reading the variables that are of type float.
scanf("%f", &loanAmt); // loanAmt is int
...
scanf("%f", &numberPay); //numberPay is int
In both wrong argument is passed to %f , therefore , causes UB . Use %d specifier .
And in this one } is missing -
if(loanAmt>monthlyPay)
{
while(count<numberPay)
{
loanAmt = loanAmt*(1 + (yearInt/12)) - monthlyPay;
count += count+1;
}
printf("The amount of last payment is: %.2f\n", loanAmt); //use %d
// ADD '}' here
else // ADD '{' here
printf("The amount of last payment is: %.2f\n", loanAmt); //use %d
}
Put a } before else {.
Related
Trying to make a GPA calculator.
Here is my code:
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
float fgpa, grade, n;
char reply;
n = 1;
grade = 1;
printf("--- GPA Calculator ---");
while(fgpa < 1 || fgpa > 4)
{
printf("\n\nEnter your current GPA: ");
scanf("%f", &fgpa);
if(fgpa < 1 || fgpa > 4)
printf("Invalid Input! Please re-enter value.");
}
printf("\nUsing the following table to convert grade to points\n\nA+ = 4.0\nA = 4.0\nB+ = 3.5\nB = 3\nC+ = 2.5\nC = 2.0\nD+ = 1.5\nD = 1\nF = 0\n");
while(grade > 0, n++)
{
printf("\nEnter points for module %.0f, enter \"0\" if there are no more additional modules: ", n);
scanf("%f", &grade);
printf("%f", grade);
fgpa = (fgpa + grade) / n;
}
fgpa = fgpa* n / (n-1);
n--;
printf("\n\nNumber of modules taken: %.0f\nFinal GPA: %.1f", n, fgpa);
return 0;
}
I've tried using if(grade = 0) break; but its still not breaking the loop even when the grade is correctly read 0.
picture of 0 being read correctly but loop still continuing
There are multiple problems in the code:
fgpa is uninitialized so the first test in the loop has undefined behavior.
you should also test the return value of scanf() to detect invalid or missing input.
while (grade > 0, n++) is incorrect too: you should instead always read the next grade and test its value and break from the loop before incrementing n.
Your averaging method seems incorrect too: you do not give the same weight to every module.
It seems more appropriate for your purpose to use for ever loops (for (;;)), unconditionally read input, check for scanf() success and test the input values explicitly before proceeding with the computations.
Here is a modified version:
#include <stdio.h>
// flush the rest of the input line, return EOF at end of file
int flush(void) {
int c;
while ((c = getchar()) != EOF && c != \n')
continue;
return c;
}
int main() {
float fgpa;
float grade;
int n = 1;
char reply;
printf("--- GPA Calculator ---");
for (;;) {
printf("\n\nEnter your current GPA: ");
if (scanf("%f", &fgpa) == 1) {
if (fgpa >= 1 && fgpa <= 4)
break;
}
} else {
if (flush() == EOF) {
fprintf(stderr, "unexpected end of file\n");
return 1;
}
}
printf("Invalid Input! Please re-enter value.\n");
}
printf("\nUsing the following table to convert grade to points\n\n"
"A+ = 4.0\nA = 4.0\nB+ = 3.5\nB = 3\nC+ = 2.5\n"
"C = 2.0\nD+ = 1.5\nD = 1\nF = 0\n");
for (;;) {
printf("\nEnter points for module %d, enter \"0\" if there are no more additional modules: ", n);
if (scanf("%f", &grade) == 1) {
if (grade <= 0)
break;
printf("%f\n", grade);
fgpa = fgpa + grade;
n = n + 1;
} else {
if (flush() == EOF)
break;
printf("Invalid Input! Please re-enter value.\n");
}
}
fgpa = fgpa / n;
printf("\n\nNumber of modules taken: %d\nFinal GPA: %.3f\n", n, fgpa);
return 0;
}
Here I have created a compounding interest calculator. The user inputs principal, interest% and duration (in quarters). I have used a for loop for the initial calculation. But, I don't know how to get the total to rollover to the next quarter's principal.
Say the user inputs 1000, 5% and 2 quarters. The output should look like, Q1 Principal=$1000, Interest=0.05, Total=$1012.50, Q2 =$1012.50 =0.05 =$1025.16
Also my last Do while is giving me some issues. The ouput is spitting out a couple extra lines before letting the user start over.
Any advice would be greatly appreciated.
Thank you
#include <stdio.h>
int main (void)
{
int a = 0, b=0;
double interest, prin, total=0;
char check = ' ';
do{
do{
do{
printf (" Please enter principal:\n");
scanf ("%lf", &prin);
}while(prin <=0);
do{
printf ("Please enter desired interest greater
than 0 less than 20 :\n");
scanf ("%lf", &interest);
}while(interest <=0 || interest >20);
interest = interest/100;
do{
printf ("For how many quarters would you like
to deposit: (more than 0, less than 40) \n");
scanf ("%d", &b);
}while(b <=0 || b >40);
printf ("Is this information correct? Press X
to continue" );
scanf ("\n%c", &check);
}while(check != 'x' && check != 'X');
total = prin * (1+(interest *.25));
printf ("Quarter Principal Interest
Total\n");
for(a=1; ;++a){
printf ("%2d $%.2f %.2lf
$%.2lf\n", a, prin, interest, total);
if(a == b)
break;
}
printf ("Do you want to start over (Y/N)?");
scanf ("%c\n", &check);
}while(check != 'y' || check != 'Y');
return 0;
}
The are some problem with indentation and logic in your code. You need to updade principle in for loop statement. Then print it out .Here is my solution
#include <stdio.h>
int main(void)
{
int a = 0, b = 0;
double interest, prin, total = 0;
char check = ' ';
do {
do {
do {
printf(" Please enter principal:\n");
scanf("%lf", &prin);
} while (prin <= 0);
do {
printf("Please enter desired interest greater than 0 less than 20 :\n");
scanf("%lf", &interest);
} while (interest <= 0 || interest > 20);
interest = interest / 100;
do {
printf("For how many quarters would you like to deposit : (more than 0, less than 40) \n");
scanf("%d", &b);
} while (b <= 0 || b > 40);
printf("Is this information correct? Press X to continue" );
scanf("\n%c", &check);
} while (check != 'x' && check != 'X');
printf("Quarter Principal Interest Total\n");
for (a = 1; a<=b; ++a) {
total = prin * (1 + (interest *.25));
printf("%2d $%.2f %.2lf $%.2lf\n", a, prin, interest, total);
prin = total;
}
printf("Do you want to start over (Y/N)?");
scanf("%c\n", &check);
} while (check != 'y' || check != 'Y');
return 0;
}
i am trying to get this program to repeat when prompted Y or N and i cant seem to get it to work right for some reason and this is the last thing i have left and im pretty sure the rest of the code is right i think all i need is it to repeat the whole program if the user enters a "Y" or just exits if the user enters "N"
int main(void)
{
// Constant and Variable Declarations
const int MPH_SPEED_MIN = 1;
const int MPH_SPEED_MAX = 100;
const int HOURS_TRAVLED_MIN = 1;
int mphSpeed = 1;
int hoursEntered = 0;
int distanceTraveled = 0;
int counterNum = 0;
int distanceNum = 0;
char ch = 'y';
// *** Input ***
do {
printf("What is the speed of the vehicle in MPH? ");
scanf("%d", &mphSpeed);
while ((mphSpeed < MPH_SPEED_MIN) || (mphSpeed > MPH_SPEED_MAX)) {
printf("\tThe speed entered must be between %d and %d inclusive
\n",MPH_SPEED_MIN, MPH_SPEED_MAX);
printf("\tPlease re-enter the speed of the vehicle in MPH: ");
scanf("%d", &mphSpeed);
}
printf("How many hours has it traveled? ");
scanf("%d", &hoursEntered);
while (hoursEntered < HOURS_TRAVLED_MIN) {
printf("\tThe hours traveled must be a positive number.\n");
printf("\tPlease re-enter the number of hours traveled: ");
scanf("%d", &hoursEntered);
}
printf("\n");
printf("Hour\tDistance Traveled\n");
distanceTraveled = hoursEntered * mphSpeed;
for (counterNum = 1; counterNum <= hoursEntered; counterNum++) {
distanceNum = distanceTraveled * counterNum;
printf("%d\t%d miles\n", counterNum, distanceNum);
}
printf("\n");
printf("Run the program again (Y/N)? ");
scanf("%c", &ch);
printf("\n");
} while (ch == 'Y' || ch == 'y');
; return 0;
When reading in with scanf(%c..., the statement very likely reads in a new line character left in the buffer from previous inputs. Read in a string instead, because %s ignores any leading white spaces (including such a new line character left in the buffer).
Try ...
char exitYN[2];
if (scanf("%1s",exitYN) != 1) {
exitYN[0]='N';
}
char ch = exitYN[0];
} while (ch == 'Y' || ch == 'y');
The one small yet, the most effective change that can be made here is adding a <space> before the %c while accepting the Y or N, i.e, scanf(" %c, &ch");
And I don't know if the following are errors while typing the code in StackOverflow, or are they originally errors in your code, but definitely are worth making changes:
Header file missing: #include<stdio.h>,
Unwanted and extra semicolon (;) before the return statement at the end,
missing closing bracket (}) at the end, after the return.
Here is the working code:
#include<stdio.h>
int main(void)
{
// Constant and Variable Declarations
const int MPH_SPEED_MIN = 1;
const int MPH_SPEED_MAX = 100;
const int HOURS_TRAVLED_MIN = 1;
int mphSpeed = 1;
int hoursEntered = 0;
int distanceTraveled = 0;
int counterNum = 0;
int distanceNum = 0;
char ch = 'y';
// *** Input ***
do {
printf("What is the speed of the vehicle in MPH? ");
scanf("%d", &mphSpeed);
while ((mphSpeed < MPH_SPEED_MIN) || (mphSpeed > MPH_SPEED_MAX)) {
printf("\tThe speed entered must be between %d and %d inclusive\n",MPH_SPEED_MIN, MPH_SPEED_MAX);
printf("\tPlease re-enter the speed of the vehicle in MPH: ");
scanf("%d", &mphSpeed);
}
printf("How many hours has it traveled? ");
scanf("%d", &hoursEntered);
while (hoursEntered < HOURS_TRAVLED_MIN) {
printf("\tThe hours traveled must be a positive number.\n");
printf("\tPlease re-enter the number of hours traveled: ");
scanf("%d", &hoursEntered);
}
printf("\n");
printf("Hour\tDistance Traveled\n");
distanceTraveled = hoursEntered * mphSpeed;
for (counterNum = 1; counterNum <= hoursEntered; counterNum++) {
distanceNum = distanceTraveled * counterNum;
printf("%d\t%d miles\n", counterNum, distanceNum);
}
printf("\n");
printf("Run the program again (Y/N)? ");
scanf(" %c", &ch);
printf("\n");
} while (ch == 'Y' || ch == 'y');
return 0;
}
I have also attached the output just in case you need to verify.
OUTPUT:
What is the speed of the vehicle in MPH? 12
How many hours has it traveled? 1
Hour Distance Traveled
1 12 miles
Run the program again (Y/N)? y
What is the speed of the vehicle in MPH? 6
How many hours has it traveled? 6
Hour Distance Traveled
1 36 miles
2 72 miles
3 108 miles
4 144 miles
5 180 miles
6 216 miles
Run the program again (Y/N)? n
I am trying to make a simple calculator in Turbo C(I have my own reasons to why I use Turbo C now)
#include <stdio.h>
#define P printf
int loop[] = {1, 1, 1, 1};
int num;
char input[64];
void main()
{
int num1, num2;
char x, y;
while(loop[0] == 1)
{
clrscr();
P("Hello!, This simple calculator will help you compute 2 numbers.");
P("\nPress the corresponding key to choose the operation you will use.");
P("\n\nA - (A)ddition");
P("\nS - (S)ubtraction");
P("\nM - (M)ultiplication");
P("\nD - (D)ivision");
P("\n\nAnswer: ");
while(loop[1] == 1)
{
x = getchar();
if(tolower(x) == 'a')
{
P("\nYou have chosen addition.");
num1 = askForNumber("\n\nEnter 1st number: ");
num2 = askForNumber("\nEnter 2nd number: ");
P("\n\n%d + %d = %d", num1, num2, num1+num2);
}
else if(tolower(x) == 's')
{
P("\nYou have chosen subtraction.");
num1 = askForNumber("\n\nEnter 1st number: ");
num2 = askForNumber("\nEnter 2nd number: ");
P("\n\n%d - %d = %d", num1, num2, num1-num2);
}
else if(tolower(x) == 'm')
{
P("\nYou have chosen multiplication.");
num1 = askForNumber("\n\nEnter 1st number: ");
num2 = askForNumber("\nEnter 2nd number: ");
P("\n\n%d * %d = %d", num1, num2, num1*num2);
}
else if(tolower(x) == 'd')
{
P("\nYou have chosen division.");
num1 = askForNumber("\n\nEnter 1st number: ");
num2 = askForNumber("\nEnter 2nd number: ");
P("\n\n%g* %g = %.2f", (float)num1, (float)num2, (float)(num1/num2));
}
else
{
P("\nYou have entered an invalid character!");
P("\n\nAnswer: ");
continue;
}
while(loop[2] == 1)
{
P("\n\nDo you want to do another calculation? Y/N: ");
y = getchar();
if(tolower(y) == 'y' || tolower(y) == 'n')
{
loop[2] = 0;
}
else
{
P("\nYou have entered an invalid character.");
continue;
}
}
loop[1] = 0;
}
if(tolower(y) == 'y')
{
continue;
}
if(tolower(y) == 'n')
{
loop[0] = 0;
}
}
}
int askForNumber(const char *string)
{
P("%s", string);
while(loop[3] == 1)
{
fgets(input, (sizeof(input)/sizeof(input[0]))-1, stdin);
if(sscanf(input, "%d", &num) != 1)
{
num = 0;
P("Invalid number!");
continue;
}
return num;
}
}
I have these bugs:
After I finish a calculation, and press 'Y', it clears the screen non-stop.
After "Enter 1st number: ", the "Invalid number" shows up once even though I haven't typed anything yet(but i can still input a number and it will be saved to 'num1', "Invalid number just bugs me".
At the top where I am to input 'a' or 's' or 'm' or 'd' to choose an operation, if I put some letter except for that above, i get this
OUTPUT:
Answer: o
You have entered an invalid character!
Answer:
You have entered an invalid character!
Answer:
the error shows up twice, but i only typed once.
When there are no characters in the input buffer, the getchar function blocks until the return key is pressed. All keys, including return, are stored in the input buffer, then getchar returns the first character in the buffer. The next call to getchar will immediately return the next character in the buffer.
So if you press 'y' then return, the first call to getchar returns the 'y' character, and the next returns a newline character, i.e. the return key.
You need to flush the input buffer each time you use getchar to skip over the newline:
do {
c = getchar();
} while (c == '\n');
You nedd #include ctype.h to lower is part of that library tolower uses this library and its nowhere in your code
Here's a part of a function that supposed to scan an integer between 0 and 100.
The program goes wrong when the user inputs a char. anyone has an idea? iv'e tried a Combined condition like this one: if(scanf("%d",&test)&&(test<=100&&test>=0))
it didn't work...
while(i!=4)
{
printf("\nPlease enter your homework grade: ");
if(scanf("%d",&hw))
{
++i;
}
if(hw<=100&&hw>=0)
{
++i;
}
printf("\nPlease enter your test grade: ");
if(scanf("%d",&test))
{
++i;
}
if(test<=100&&test>=0)
{
++i;
}
else
{
printf("\nPlease re-enter the required details\n");
i=0;
}
}
When a character is read using %d then the ASCII value of it is stored in the memory.
If you want a Integer Proofing mechanism, then use the below code. Get the user input as a string, check if any character is present, if present then return error, else convert that string to integer and use the same for further processing.
char n[4]; /* To store max of 3 char's `100` including '\0' */
int i=0, flag=1;
scanf("%3s", n);
while(n[i] != '\0'){
flag = isdigit(n[i]);
if (!flag)
break;
i++;
}
if(flag)
{
i=atoi(n);
printf("%d", i);
}
else
{
printf("it's not integer");
}
you have to make while(i!=2){....}
Try the program in this way....
main()
{
int i, hw, test;
while(i!=2)
{
i=0;
printf("\nEnter the hmwrk grade: ");
if(scanf("%d",&hw)&&(hw<=100&&hw>=0))
++i;
printf("\nEnter the test grade: ");
if(scanf("%d",&test)&&(test<=100&&test>=0))
++i;
if(i!=2)
printf("\nPlease reenter the req details..\n");
}
}