Deposit gives negative number? - c

Good morning, guys! I'm currently a newly started programming learner. Down here is my code for a mini app store. However, there is a problem going on, yet I couldnt locate the problem.
The problem happen when I tried buying an app for $89.99 and I chose to redeem $10 9 times so I would have enough money to purchase the app (I didnt choose the $100 option because it would work just fine). However, the remained amount became $-79.99 instead of $0.01. Like I said, if I chose to deposit $100, the remained balance would be $10.01, which is normal. I don't get where I did wrong. Here is my code!
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <ctype.h>
int Compare(double deposit, double choiceCost);
void DisplayApps(char *selectionPtr);
void SetCost(char selection, double *costPtr);
void PaymentOptions(double *depositPtr,double cost);
void DoItAgain(char *quitPtr);
//void Pay(double *depositPtr, double choiceCost);
void GetChange(double *depositPtr, double choiceCost);
void DoItAgain(char *quitPtr);
int main()
{
char selectionPtr;
char selection;
char quitPtr;
double costPtr;
double deposit = 0.0;
double choiceCost;
double depositPtr = 0.0;
double cost = 0.0;
printf("Welcome to the App Store\n");
printf("***************************\n\n");
printf("Your deposit is: %.2f\n", deposit);
printf("\n");
while (1)
{
do {
DisplayApps(&selectionPtr);
selection = selectionPtr;
SetCost(selection, &costPtr);
choiceCost = costPtr;
Compare(deposit, choiceCost);
while (Compare(deposit, choiceCost) == 0)
{
printf("Your balance isn't enough.\n");
printf("In order to purchase this item, you have to redeem more money.\n");
PaymentOptions(&depositPtr, cost);
deposit += depositPtr;
printf("You have redeemed $%.2f\n", depositPtr);
printf("Your balance now is: $%.2f\n", deposit);
printf("\n");
}
deposit = depositPtr;
GetChange(&depositPtr, choiceCost);
DoItAgain(&quitPtr);
} while (quitPtr == 'Y' || quitPtr == 'y');
return 1;
}
return 0;
}
void DisplayApps(char *selectionPtr)
{
printf("-------------------------\n");
printf("HERE ARE THE SLECTIONS\n");
printf("C -- Clown Punching $299.99\n");
printf("V -- Virtual Snow Globe $349.99\n");
printf("R -- Remote PC $999.99\n");
printf("G -- Grocery List Helper $2.99\n");
printf("M -- Mobile Cam Viewer $89.99\n");
printf("\n");
printf("Please enter a selection: ");
scanf(" %c", &*selectionPtr);
printf("\n");
}
void SetCost(char selection, double *costPtr)
{
if (selection == 'C' || selection == 'c')
{
*costPtr = 299.99;
}
else if (selection == 'V' || selection == 'v')
{
*costPtr = 349.99;
}
else if (selection == 'R' || selection == 'r')
{
*costPtr = 999.99;
}
else if (selection == 'G' || selection == 'g')
{
*costPtr = 2.99;
}
else if (selection == 'M' || selection == 'm')
{
*costPtr = 89.99;
}
}
int Compare(double deposit, double choiceCost)
{
if (deposit < choiceCost)
{
return 0;
}
else
{
return 1;
}
}
void PaymentOptions(double *depositPtr, double cost)
{
printf("You have (4) options to choose:\n");
printf("1 - $1000.00\n");
printf("2 - $500.00\n");
printf("3 - $100.00\n");
printf("4 - $10.00\n");
printf("How much do you want to redeem?");
printf(">>>>> ");
scanf("%lf", &cost);
printf("\n");
printf("-------------------------------------\n");
if (cost == 1)
{
*depositPtr = 1000.00;
}
else if (cost == 2)
{
*depositPtr = 500.00;
}
else if (cost == 3)
{
*depositPtr = 100.00;
}
else if (cost == 4)
{
*depositPtr = 10.00;
}
}
void GetChange(double *depositPtr, double choiceCost)
{
*depositPtr = *depositPtr - choiceCost;
printf("You have purchased this item successfully.\n");
printf("You still have $%.2f remained in you balance.\n", *depositPtr);
}
void DoItAgain(char *quitPtr)
{
printf("Do you want to continue purchase another item? [Y/N]\n");
scanf(" %c", &*quitPtr);
}

In this code : GetChange(&depositPtr, choiceCost);
You shold pass deposit (total deposit) and not &depositPtr (last deposit, only 10)

Related

Morra - Odds and Even

Im writing a code that evolves the computer and I entering numbers and added them together to see who wins.
There are three problems:
Problem 1: When I try to recall the 'main()' function the 'game()' wont appear.
Problem 2: I can't seem to run the code forever until user decides to stop.
Problem 3: The point system isn't accurate enough.
Any help would be grateful.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int human_fingers;
int comp_fingers;
int menu_choice;
int answer;
int count = 1;
int point1 = 0, point2 = 0;
int total;
void intro() {
printf("Welcome to Morra - Odds and Even!\n\n");
printf("The rules of the game are pretty simple\n");
printf("You and the computer will pick a side each round\n");
printf("You must enter a number and the total sum will determine the winner!\n\n");
}
void example() {
printf("You picked even, by default the computer will be odd this round\n");
printf("You entered 3 and the computer entered 5\n");
printf("3 + 5 = 8, so you win because you choose even!\n");
}
void game() {
while(count < 7)
{
count = count + 1;
printf("Enter a number to choose a side:\n");
printf("Even [1] / Odd [2]\n");
scanf("%d", &menu_choice);
while((menu_choice<1) || (menu_choice>2)){
printf("Invalid entry, please Enter 1-2: ");
scanf("%d",&menu_choice);}
if(menu_choice == 1)
{
printf("The computer will be odd this turn\n");
printf("\nPlease enter an number (1-10)\n");
scanf("%d", &human_fingers);
while((human_fingers<1) || (human_fingers>10)){
printf("Invalid entry, please enter 1-10:");
scanf("%d",&human_fingers);}
printf("Computer is choosing a number....\n");
srand(time(NULL));
comp_fingers = rand() % 10 + 1;
printf("You: %d\n", human_fingers);
printf("Computer: %d\n", comp_fingers);
int result;
result = human_fingers + comp_fingers;
printf("Total is %d\n", result);
total = result % 2;
if(total == 0)
{
printf("This turn goes to You!\n\n");
printf("You: %d\n", point1 + 1);
printf("Computer: %d\n\n", point2 + 0 );
point1++;
}
else
{
printf("This turn goes to Computer!\n\n");
printf("You: %d\n", point1 + 0 );
printf("Computer: %d\n\n", point2 + 1);
point2++;
}
}
if(menu_choice == 2)
{
printf("The computer will be even this turn\n");
printf("\nPlease enter an number (1-10)\n");
scanf("%d", &human_fingers);
while((human_fingers<1) || (human_fingers>10)){
printf("Invalid entry, please enter 1-10:");
scanf("%d",&human_fingers);}
printf("Computer is choosing a number...\n");
srand(time(NULL));
comp_fingers = rand() % 10 + 1;
printf("You: %d\n", human_fingers);
printf("Computer: %d\n", comp_fingers);
int result;
result = human_fingers + comp_fingers;
printf("Total is %d\n", result);
total = result % 1;
if(total == 0)
{
printf("This turn goes to Computer!\n\n");
printf("You: %d\n", point1 + 0);
printf("Computer: %d\n\n", point2 + 1);
point1++;
}
else
{
printf("This turn goes to You!\n\n");
printf("You: %d\n", point1 + 1);
printf("Computer: %d\n\n", point2 + 0 );
point2++;
}
}
}
if(point1 > point2)
printf("You won, you beat the computer!\n");
else
printf("Unlucky the computer won!\n");
}
void end(){
printf("Game has ended!\n");
}
int main()
{
intro();
printf("Would you like an example to demostrate?\n");
printf("Yes [1] / No [2]\n");
scanf("%d", &answer);
if( answer == 1 )
{ example();
printf("\n\n");
game();
}
else
{ printf("\n\n");
game();
}
end();
printf("Would you like play another game?\n");
printf("Yes [1] / No [2]\n");
scanf("%d", &answer);
if( answer == 1)
{
main();
}
else {
printf("Thanks for playing MORRA - ODDS AND EVEN.");
}
return 0;
}
Why not:
int main()
{
for(;;) // Infinite loop. -- equivalent of while(1) if you prefer.
{
intro();
printf("Would you like an example to demostrate?\n");
printf("Yes [1] / No [2]\n");
scanf("%d", &answer);
if( answer == 1 )
{ example();
printf("\n\n");
game();
}
else
{ printf("\n\n");
game();
}
end();
printf("Would you like play another game?\n");
printf("Yes [1] / No [2]\n");
scanf("%d", &answer);
if( answer != 1)
{
printf("Thanks for playing MORRA - ODDS AND EVEN.");
break;
//^___ exit the infinite loop.
}
}
return 0;
}
Recalling the main you should definitely not, in almost any case. Just create loops if you want to repeat everything.

Need to get the output only when the loop ends

Here, i want to get the output only after the user enters the letter 'Q', which is the last task of my program. However, when i enter 'R' which is another case for my program, it directly prints the output for me.
int main() {
float amountOfTurkishLira = 0;
float amountOfBtc = 0;
float amountOfEth = 0;
char operationCode;
char operationTurkishLira;
// getting the amount of money for the initial money;
scanf(" %c", &operationTurkishLira);
if (operationTurkishLira != 'T') {
printf("Error: Operation could not be completed.");
} else {
scanf(" %f", &amountOfTurkishLira);
scanf(" %c", &operationCode);
while (operationCode != 'Q') {
switch (operationCode) {
case 'R':
if (amountOfBtc == 0 && amountOfEth == 0) {
printf("Our account holds %.2f TRY", amountOfTurkishLira);
} else {
printf("Our account holds %.2f TRY | %.2f BTC | %.2F ETH.", amountOfTurkishLira, amountOfBtc,
amountOfEth);
}
scanf(" %c", &operationCode);
break;
}
}
printf("Bye..");
}
return 0;
}
This happens when i enter the input:
T
1000
R
Our account holds 1000.00 TRY
Bye...
But I want it to be like this:
T
1000
R
Q
after i enter all my input, it should give me
Our account holds 1000.00 TRY
Bye...
Take the printing code out of the loop and do it at the end.
And take scanf(" %c", &operationCode); out of the switch, since it should be done no matter what the previous code was.
int main() {
float amountOfTurkishLira = 0;
float amountOfBtc = 0;
float amountOfEth = 0;
char operationCode;
char operationTurkishLira;
// getting the amount of money for the initial money;
scanf(" %c", &operationTurkishLira);
if (operationTurkishLira != 'T') {
printf("Error: Operation could not be completed.");
} else {
scanf(" %f", &amountOfTurkishLira);
scanf(" %c", &operationCode);
while (operationCode != 'Q') {
switch (operationCode) {
case 'R':
break;
}
scanf(" %c", &operationCode);
}
if (amountOfBtc == 0 && amountOfEth == 0) {
printf("Our account holds %.2f TRY", amountOfTurkishLira);
} else {
printf("Our account holds %.2f TRY | %.2f BTC | %.2F ETH.", amountOfTurkishLira, amountOfBtc,
amountOfEth);
}
printf("Bye..");
}
return 0;
}
Take a look on my version. I have some comments in it. You just have to add your logic for the case you pressing 'R' or an other key (I suppose you will add some more key press listeners).
#include <stdio.h>
int main() {
float amountOfTurkishLira = 0;
float amountOfBtc = 0;
float amountOfEth = 0;
char operationCode;
char operationTurkishLira;
// getting the amount of money for the initial money;
scanf(" %c", &operationTurkishLira);
if (operationTurkishLira != 'T') {
printf("Error: Operation could not be completed.");
}
else {
scanf(" %f", &amountOfTurkishLira);
scanf(" %c", &operationCode);
while (operationCode != 'Q') {
switch (operationCode) {
case 'R':
if (amountOfBtc == 0 && amountOfEth == 0) {
printf("LOGIC FOR amountOfBtc == 0 && amountOfEth == 0\n");
} else {
printf("LOGIC FOR amountOfBtc != 0 || amountOfEth != 0\n");
}
break;
case 'X': // X, Y, or WHATEVER
// LOGIC FOR 'X'
break;
}
scanf(" %c", &operationCode);
}
if (operationCode == 'Q') {
if (amountOfBtc == 0 && amountOfEth == 0) {
printf("Our account holds %.2f TRY\n", amountOfTurkishLira);
}
else {
printf("Our account holds %.2f TRY | %.2f BTC | %.2F ETH.\n", amountOfTurkishLira, amountOfBtc, amountOfEth);
}
printf("Bye..");
}
}
return 0;
}

How can I restart the program in C?

Hi I'm new to C and I wrote a simple program. I want to restart the program if the user picked the wrong choice, here is the code:
#include <stdio.h>
#include <cs50.h>
int main(void){
char choices;
float math, pc, svt, eng, philo;
do {
do {
printf("Enter your math score: ");
math = GetFloat();
}
while( math>20 || math<0);
do {
printf("Enter your pc score: ");
pc = GetFloat();
}
while(pc>20 || pc<0);
do {
printf("Enter your svt score: ");
svt = GetFloat();
}
while(svt>20 || svt<0);
do {
printf("Enter your eng score: ");
eng = GetFloat();
}
while(eng>20 || eng<0);
do {
printf("Enter your philo score: ");
philo = GetFloat();
}
while(philo>20 || philo<0);
printf("Are you pc or sm?\n");
printf("Write 1 for pc. 2 for sm\n");
int choice = GetInt();
if(choice == 1){
float score = (math*7 + pc*7 + svt*7 + eng*2 + philo*2)/25;
printf("Your score is %.2f\n", score);
}
else if(choice == 2){
float score = (math*9 + pc*7 + svt*3+ eng*2 + philo*2)/23;
printf("Your score is %.2f\n", score);
}
else{
printf("You've picked the wrong choice \n");
}
printf("Do you want to try it again? (Y/N) ");
choices = getchar();
while (choices != '\n' && getchar() != '\n') {};
} while (choices == 'Y' || choices == 'y');
}
So what I mean here, I want to insert the code in the else block to restart the program and give the user another time. It would be very nice if I can just make him choose again between 1 or 2.
If you have any suggestions or improvement please don't hesitate to comment.
Thanks :)
What you need is do while loop surrounding choice code:
int choice;
do {
choice = GetInt();
if (choice == 1) {
float score = (math*7 + pc*7 + svt*7 + eng*2 + philo*2)/25;
printf("Your score is %.2f\n", score);
}
else if (choice == 2) {
float score = (math*9 + pc*7 + svt*3+ eng*2 + philo*2)/23;
printf("Your score is %.2f\n", score);
}
else {
printf("You've picked the wrong choice, try again.\n");
}
} while(choice < 1 || choice > 2)
You already have a loop to try again, you can reuse that loop to get the user input again for choice. So, if the user enters choice other than 1 or 2, you can set choices = Y and redo the loop. without asking for user input.
Code is below.
#include <stdio.h>
#include <cs50.h>
int main(void)
{
char choices;
float math, pc, svt, eng, philo;
do
{
// Other code here
int choice = GetInt();
if(choice == 1){
float score = (math*7 + pc*7 + svt*7 + eng*2 + philo*2)/25;
printf("Your score is %.2f\n", score);
}
else if(choice == 2){
float score = (math*9 + pc*7 + svt*3+ eng*2 + philo*2)/23;
printf("Your score is %.2f\n", score);
}
else{
printf("You've picked the wrong choice \n");
choices = 'Y';
}
if ((choice == 1) || (choice == 2))
{
printf("Do you want to try it again? (Y/N) ");
choices = getchar();
while (choices != '\n' && getchar() != '\n') {};
}
} while (choices == 'Y' || choices == 'y');
}
Well, if somebody reading this has to actually restart their program for a more nontrivial reason (e.g. an exception handler, like me a couple of minutes ago), there is a portable way to to so in C, like so:
#include <setjmp.h> //from C standard library
jmp_buf restart_env;
int main() {
//some initialization you don't want to repeat
if(setjmp(restart_env)) {
//restarted, do whatever
}
//the code
}
void evenFromAnotherFunction() {
//...
if(something_that_justifies_this_approach) {
longjmp(restart_env, 1); //this restarts the program
//unreachable
}
//...
}
Note that you had better not use this if there's a better way. Using setjmp is bound to produce extremely annoying bugs. If you have no choice, remember that some data may preserve the value it had before calling setjmp for the first time, and some may not, so don't assume anything.

Banking Program, withdraw function doesn't work? (C)

for some reason I can't get the withdraw function to work in my banking program... I thought I was doing it correct as the functions can be very similar to the deposit function.
The problem is I can't seem to get a withdraw amount without the program even building correctly. The withdraw function should be very similar to the deposit function correct? Because instead of depositing a value into the account, you're simply withdrawing an amount from the given account. If the account doesn't have enough money, then it returns as an error. Here's my code:
#include <stdio.h>
#include <stdlib.h>
#define MAXNUMCUSTOMERS 10 // Maximum number of customers
#define MAXCUSTOMERNAME 20 // Max length of customer's name including null character at the end
// Function Prototypes
int DisplayMenu();
int userLogin(int acctNumber[MAXNUMCUSTOMERS]);
float acctBalance (int custIndex, float money[MAXNUMCUSTOMERS]);
float depositMoney (int custIndex, float money[MAXNUMCUSTOMERS]);
float withdrawFunds (int custIndex, float money[MAXNUMCUSTOMERS]);
/*
*
*/
int main(int argc, char** argv) {
int acctNumber[MAXNUMCUSTOMERS] =
{1111,2222,3333,4444,5555,6666,7777,8888,9999,10000};
char customerName[MAXNUMCUSTOMERS][MAXCUSTOMERNAME] =
{"Joe","Mary","bob","tim","sid","will","ray","les","quinn","helen"};
float money[MAXNUMCUSTOMERS] =
{12.50,25.30,69.3,46.0,777.00,10000.,55.6,33.78,99.54,47895.33};
int option = 0;
int myAcct = -1;
float myBalance = 0.0;
// loop until done
while (option != 6) {
// Display menu - return option
option = DisplayMenu();
if (option == 0) { // customer login
myAcct = userLogin(acctNumber);
if (myAcct == -1) {
printf("Invalid account\n");
} else {
printf ("Welcome %s \n", customerName[myAcct]);
}
} else if (option == 1) { // deposit money
myBalance = depositMoney (myAcct, money);
if (myBalance < 0.0)
printf("Account not found\n");
else
printf ("Your new account balance is: %.2f\n", myBalance);
} else if (option == 2) { // withdraw money
if (myBalance > 0.0)
printf("Account not found\n");
else
printf ("Your new account balance is: %.2f\n", myBalance);
} else if (option == 3) { // account balance
myBalance = acctBalance (myAcct, money);
if (myBalance < 0.0)
printf("Account not found\n");
else
printf ("Your account balance is: %.2f\n", myBalance);
} else if (option == 4) { // add a customer
} else if (option == 5) { // delete a customer
} else if (option == 6) { // exit
}
// exit program
} //end loop until done
return (EXIT_SUCCESS);
}
int DisplayMenu() {
int customerChoice;
printf("Welcome to My Bank\n");
printf("Enter an option from the menu\n");
printf("\t 0 Customer Login\n");
printf("\t 1 Deposit Money Login\n");
printf("\t 2 Withdraw Money\n");
printf("\t 3 Account Balance\n");
printf("\t 4 Add a customer\n");
printf("\t 5 delete a customer\n");
printf("\t 6 Exit\n");
scanf("%d", &customerChoice);
return (customerChoice);
}
int userLogin(int acctNumber[MAXNUMCUSTOMERS])
{
int customerIndex = -1;
int accountNum;
int i;
// get the account number
printf("Please enter your account number>");
scanf("%d", &accountNum);
// loop to find which index has customer information
for (i=0; i < MAXNUMCUSTOMERS; i++)
{
if (accountNum == acctNumber[i])
customerIndex = i;
} // end loop
return customerIndex;
}
float acctBalance (int custIndex, float money[MAXNUMCUSTOMERS])
{
float balance = -1.0;
if (custIndex >= 0)
balance = money[custIndex];
return balance;
}
float depositMoney (int custIndex, float money[MAXNUMCUSTOMERS])
{
float balance = -1.0;
float deposit;
if (custIndex >= 0)
{
// get the deposit amount
printf ("Enter Deposit Amount>");
scanf ("%f", &deposit);
money[custIndex] = money[custIndex] + deposit;
balance = money[custIndex];
}
return balance;
}
//my problem is down here. This section doesn't work???
float withdrawFunds (int custIndex, float money[MAXNUMCUSTOMERS];
{
float balance = -1.0;
float withdraw;
if (custIndex >= 0)
{
//get withdraw amount
printf ("Enter Withdraw Amount>");
scanf ("%f", %withdraw);
money[custIndex] = withdraw - money[custIndex];
balance = money[custIndex];
}
return balance;
}
Try this. ( checking whether the account has enough money isn't implemented here)
float withdrawFunds (int custIndex, float money[MAXNUMCUSTOMERS]) // ; -> )
{
float balance = -1.0;
float withdraw;
if (custIndex >= 0)
{
//get withdraw amount
printf ("Enter Withdraw Amount>");
scanf ("%f", &withdraw); // % -> &
money[custIndex] = money[custIndex] - withdraw ; // correct the formula
balance = money[custIndex];
}
return balance;
}

C programming help - Adding Values together

So I have this code but I'm missing something and I can't quite seem to get it. The point of this is to prompt the user for a selection. They pick the food that they want to order, and it tells them it is added. When the user hits 0 the program ends by saying what the total is of all the items they chose. For some reason when I hit the end, it just states the total of the last item added. Any ideas on how to fix this so that the totals all add up?
#include<stdio.h>
#define SALES_TAX .06
int selection;
double total;
double amount;
int i;
double getPrice(int selection);
void printOptionName(int selection);
void printMenu();
double getPrice(int selection){
if (selection == 1){
amount = 5.99;
} else if (selection == 2){
amount = 6.99;
} else if (selection == 3){
amount = 7.99;
} else if (selection == 4){
amount = 10.50;
} else if (selection == 5){
amount = 3.50;
}
}
void printOptionName(int selection){
if (selection == 0){
printf("\nYour total is: ");
} else if (selection == 1){
printf("\nAdded a Small Pizza\n\n");
} else if (selection == 2){
printf("\nAdded a Medium Pizza\n\n");
} else if (selection == 3){
printf("\nAdded a Large Pizza\n\n");
} else if (selection == 4){
printf("\nAdded an order of Wings\n\n");
} else if (selection == 5){
printf("\nAdded a Drink\n\n");
} else
printf("Not a valid selection. Please select one of the following options: \n");
}
void printMenu(){
printf("0. (Complete Order)\n");
printf("1. Small Pizza ****** 5.99\n");
printf("2. Medium Pizza ****** 6.99\n");
printf("3. Large Pizza ****** 7.99\n");
printf("4. Wings ****** 10.50\n");
printf("5. Drink ****** 3.50\n");
printf("Enter the Number of your selection: \n");
}
int main(){
printMenu();
scanf("%d", &selection);
printOptionName(selection);
getPrice(selection);
while (selection != 0){
printMenu();
scanf("%d", &selection);
printOptionName(selection);
getPrice(selection);
}
for (i = 0; i <= selection; i++){
total = total + amount;
}
printf("%lf\n", total);
return 0;
}
global variables are just not a good way to go. notice that you don't use selection in printmenu(), for example; you may want to pass the necessary data as arguments to a function. Also, you seem to be passing by reference in a function that passes by value. Notice that your program doesn't stop if it goes to the else statement in printOptionName(), or in getPrice(), selection will still be zero...

Resources