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;
}
Related
I need help fixing my code. What my code does it asking users to input a number multiple times and will terminate the program once -1 is entered. Then, will get the Sum, Max, Min, Average and Median values.
Sum, Min and Max seems to be working fine. But on the "Average" it's treating the -1 as a userinput, also, I need help on how to get the median value.
Here's what I got so far.
#include <stdio.h>
int main(){
char name[30];
int userInput;
int count = 0;
int sum = 0; // changed from 1 to 0
int max, min = 1000;
float average;
printf("Please enter your name: ");
scanf("%s", &name);
printf("Hello, %s, ", name);
do {
printf("Enter an integer (-1 to quit): ");
scanf("%d", &userInput);
if (userInput == -1) break; // I added this line, average works fine now
sum = sum + userInput;
count = count + 1;
average = sum / count;
if (userInput > max){
max = userInput;
}
if (userInput < min && userInput >= 0){
min = userInput;
}
}
while (userInput >= 0);
printf("Sum: %d \n", sum);
printf("Average: %.2f \n", average);
printf("Max: %d \n", max);
printf("Min: %d \n", min);
return 0;
}
Here's my sample output:
Please enter your name: A
Hello, A, Enter an integer (-1 to quit): 10
Enter an integer (-1 to quit): 20
Enter an integer (-1 to quit): 10
Enter an integer (-1 to quit): -1
Sum: 40
Average: 10.00
Max: 20
Min: 10
So The rest seems to be working now after some modification except for getting the median value.
You do not want to increment the count when userInput == -1
You're incrementing the count and adding to the sum before checking whether userInput == -1. Try rewriting your loop:
while(1){
printf("Enter an integer (-1 to quit): ");
scanf("%d", &userInput);
if(userInput == -1)
break;
/* rest of loop body goes here */
}
I'm new on Stackoverflow and I'm very, completely new to coding. Just messing around with C. Here's what I'm trying to do here (don't take this program scientifically accurate), this is a program that calculates for special relativity equations of length, mass and time. I have 3 questions actually:
When I try to put other characters in the y/n questions, everything works but for example if I enter "sfkl", the warning comes up 4 times because I entered 4 characters. And if I put space, it doesn't even give a warning until I put another character and then enter. Can I make it give 1 warning no matter how many characters I enter in one line (including space)?
My other question is, I kind of prevented inputting anything other than y/n but for the double value inputs (mass, length and time), I can't figure out a similar system (asking for a double value over and over again). Can you suggest me a solution?
And my third question is, when doing "scanf_s(" %c", &answer);", if I don't put a space before "%c", it doesn't work properly. It registers an enter and asks me to enter y/n only. Why need a space before that?
Here's the code:
#include <stdio.h>
#include <math.h>
#define LIGHT 299792458
int input();
int main()
{
printf("\n\n\tThis program calculates how length, mass and time changes with respect to your speed.\n\n\tThe values you enter are the quantites which are observed by a stationary observer and the output values are the quantites observed by the person in a vehicle which is moving at the speed that you enter.");
input();
return 0;
}
int input()
{
double length, mass, utime, speed;
char answer;
do
{
printf("\n\n **************************************************");
printf("\n\n\tPlease enter a quantity of length: ");
scanf_s("%lf", &length);
printf("\n\tPlease enter a quantity of mass: ");
scanf_s("%lf", &mass);
printf("\n\tPlease enter a quantity of time: ");
scanf_s("%lf", &utime);
printf("\n\tNow enter the speed of the vehicle (m/s): ");
scanf_s("%lf", &speed);
while (speed > LIGHT)
{
printf("\n\n\tNothing can surpass the speed of light in the universe. Enter a smaller value: ");
scanf_s("%lf", &speed);
}
double newlength = length * (sqrt(1 - pow(speed, 2) / pow(LIGHT, 2)));
double newmass = mass / (sqrt(1 - pow(speed, 2) / pow(LIGHT, 2)));
double newutime = utime / (sqrt(1 - pow(speed, 2) / pow(LIGHT, 2)));
if (speed == LIGHT)
{
printf("\n\n **************************************************");
printf("\n\n\n\tIt's technically impossible to reach the speed of light if you have mass but here are the mathematical limit results:\n\n\t*The new length quantity is 0\n\n\t*The new mass quantity is infinity\n\n\t*The new time quantity is infinity\n\n\n\t- Time successfully dilated -\n\n");
printf("\n\tDo you want to start over? (y/n): ");
scanf_s(" %c", &answer);
if (answer == 'n')
{
return 0;
}
else if (answer == 'y')
{
continue;
}
else
{
while (answer != 'y' && answer != 'n')
{
printf("\n\tPlease only enter 'y' or 'n': ");
scanf_s(" %c", &answer);
}
}
}
if (speed < LIGHT)
{
printf("\n\n **************************************************");
printf("\n\n\n\t*The new length quantity is %.20lf\n\n\t*The new mass quantity is %.20lf\n\n\t*The new time quantity is %.20lf\n\n\n\t- Time successfully dilated -\n\n", newlength, newmass, newutime);
printf("\n\tDo you want to start over? (y/n): ");
scanf_s(" %c", &answer);
if (answer == 'n')
{
return 0;
}
else if (answer == 'y')
{
continue;
}
else
{
while (answer != 'y' && answer != 'n')
{
printf("\n\tPlease only enter 'y' or 'n': ");
scanf_s(" %c", &answer);
}
}
}
}
while (answer == 'y');
return 0;
}
Thank you, have a good day
The return value of scanf is the number of elements parsed successfully; you can use this to repeat until something has been read successfully:
double nr=0;
while (!feof(stdin) && scanf("%lf",&nr)!=1) {
printf("not a number; try again.");
while ( (c = getchar()) != '\n' && c != EOF ) { }
}
Note that you have to take "invalid" input out of the buffer; otherwise, scanf would fail again and again.
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
The code is supposed to ask the user whether to find the sum of numbers from 1 to x or finding the factorial of x. After taking the user's input for the value of x, the program directly ends without running the if and else if statement. This is my code.
#include <stdio.h>
int sum(int num);
int fact(int num);
int main(void)
{
int x = 0;
char choice;
printf("Enter a number : \n");
scanf("%d", &x);
printf("Enter f for factorial, s for sum \n");
choice = getchar();
//These lines are ignored by C
if (choice == 'f' || choice == 'F')
{
printf("The factorial of %i is %i \n",x, fact(x));
}
else if (choice == 's' || choice == 'S')
{
printf("The sum from 1 to %i is %i \n",x, sum(x));
}
}
int sum (int num)
{
int sum =0;
for (int i =1; i <=num; i++ )
sum = sum+i;
return sum;
}
int fact (int num)
{
int fact =1;
for (int i =1; i <=num; i++ )
fact = fact*i;
return fact;
}
Can anyone please explain to me what is wrong with my code and how can I fix it? Thank you.
I think buffer problem. So, use
scanf(" %d", &x);
^^^
white-space
instead of
scanf("%d", &x);
and also, use
scanf(" %c", &choice);
instead of
choice = getchar();
The problem in this code is in getchar() function.
In first scanning : scanf("%d", &x); when user press enter key, it remain in the input buffer and the integer val is stored in variable x.
In second scanning: choice = getchar();, it reads the enter key in variable choice.
And you have written only two conditions:
if (choice == 'f' || choice == 'F')
else if (choice == 's' || choice == 'S')
That's why it is directly ending the code; as there is no code written for choice = other than 'f' and 's'
if you write 'else' part like this:
else printf("%d", choice);
It will print: 10 which is the ascii value of Enter / New line feed.
To avoid this, try to make following changes in your code:
int x = 0;
char choice;
printf("Enter a number : \n");
scanf("%d", &x); //here the integer is scanned in variable 'x'
choice = getchar(); //here the enter key is scanned in variable 'choice' so now input buffer is free
printf("Entr f for factorial, s for sum \n");
scanf("%c", &choice); //here the character entered by use will be stored in variable 'choice' so it is overwritten.
#include <stdio.h>
#include <time.h>
int main (void)
{
int pickedDoor, remainingDoor, hostDoor, winningDoor, option, games = 0, wins = 0;
float frequency = 0;
srand (time(NULL));
while (1)
{
printf ("Pick one of the three doors infront of you, which do you want?\n");
scanf ("%d", &pickedDoor);
if (pickedDoor > 3 || pickedDoor <= 0)
{
break;
}
winningDoor = rand() % 3 + 1;
do
{
hostDoor = rand() % 3 + 1;
} while (hostDoor == pickedDoor || hostDoor == winningDoor);
do
{
remainingDoor = rand() % 3+1;
} while (remainingDoor == pickedDoor || remainingDoor == hostDoor);
printf ("The door the host picked is %d\n", hostDoor);
do
{
printf("Do you want to switch doors? Please enter in the door you want:\n", hostdoor);
scanf("%d", &option);
if (option > 3 || option <= 0)
{return 0;}
}while (option == hostDoor);
if (option == winningDoor)
{
printf("You Won!\n");
wins++;
}
else
{
printf("YOU LOSE!\n");
}
games++;
}
frequency = ((float) wins / games) *100;
printf ("The number of games that you won is %d\n", wins);
printf ("The frequency of winning is %.0f%%\n", frequency);
return 0;
}
Hi, this is my version of the monty hall game show, im getting unexpected results though.
sometimes when I enter in a door for my option it just brings me back to the "pick one of the three doors infront of you" statement, when it should tell me if i have won or lost.
I think this is because the "option" door is equal to the "hostDoor.
I thought having "option != hostDoor" would fix it but it does not.
If i am correct in that assumption how can I fix it? If not why is it not working and how can I fix it?
To simulate correctly, OP needs to show the host door.
do {
printf("Do you want to switch doors? Please enter in the door you want:\n");
scanf("%d", &option);
if (option > 3 || option <= 0 ) {
return 0;
}
} while (option == hostDoor);
// instead of
#if 0
printf("Do you want to switch doors? Please enter in the door you want:\n");
scanf("%d", &option);
if (option > 3 || option <= 0 ) { return 0; }
#endif
To deal with OP " it should tell me if i have won or lost." problem, change
else if (option == remainingDoor)
to
else
Your scanf("%d", &option) is OK. I prefer the fgets()/sscanf() combo and its alway useful to check the result of scanf() family, but that is not your issue here.
Its because of these:
scanf ("%d", &pickedDoor);// reads \n after the last input
scanf("%d", &option); // reads \n after the last input
**option != hostDoor; // completely useless .. get rid of it**
I would suggest putting a getchar() after each scanf to get rid of the \n character
so something like this:
#include <stdio.h>
#include <time.h>
int main (void)
{
int pickedDoor, remainingDoor, hostDoor, winningDoor, option, games = 0, wins = 0;
char collect; //variable to collect any extra input like \n
float frequency = 0;
srand (time(NULL));
while (1)
{
printf ("Pick one of the three doors infront of you, which do you want?\n");
scanf ("%d", &pickedDoor);
collect = getchar(); // get rid of the \n from the input stream
printf("collect = %c\n",collect);
if(collect!='\n'){ // is it actually a \n or did you take in something else
putchar(collect); // if it isn't \n put it back
}
if (pickedDoor > 3 || pickedDoor <= 0)
{
break;
}
winningDoor = rand() % 3 + 1;
do
{
hostDoor = rand() % 3 + 1;
} while (hostDoor == pickedDoor || hostDoor == winningDoor);
do
{
remainingDoor = rand() % 3+1;
} while (remainingDoor == pickedDoor || remainingDoor == hostDoor);
printf("Do you want to switch doors? Please enter in the door you want:\n");
scanf("%d", &option);
collect = getchar(); // get rid of the \n from the input stream
printf("collect = %c\n",collect);
if(collect!='\n'){ // is it actually a \n or did you take in something else
putchar(collect); // if it isn't \n put it back
}
if (option > 3 || option <= 0 )
{
return 0;
}
if (option == winningDoor)
{
printf("You Won!\n");
wins++;
}
else if (option == remainingDoor)
{
printf("YOU LOSE!\n");
}
games++;
}
frequency = ((float) wins / games) *100;
printf ("The number of games that you won is %d\n", wins);
printf ("The frequency of winning is %.0f%%\n", frequency);
return 0;
}
Another more efficient way would be to use fgets or to have error checks on scanf() itself
srand and rand belongs to stdlib header file
#include<stdlib.h> // include this header file
option != hostDoor; // this statement does not do anything
and your else if (option == remainingDoor) should be else { printf("you lose");}