Issue with Fabs() and Abs() - c

My program checks to see if the max price is bigger than the price you spent. If the max price is bigger than the price you spent it turns the absolute value of two floats; but when I use fabs(), returns "Wow, you overspent on that first cupcake...you owe $0.00. Bye!".
I also tried abs(), but that didn't work.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main(int argc, char**argv)
{
float maxPrice;
char flavor[20];
char flavor2[20];
float price;
double price2;
char anotherCupcake[20];
double newPrice;
newPrice=maxPrice-price;
// int idxToDel = 2;
//memove(&word[idxToDel], &word[idxToDel + 1], strlen(word) - idxToDel);
printf("Please enter starting budget: ");
scanf("%f", &maxPrice);
printf("Enter the flavor of cupcake 1: ");
scanf("%s", &flavor);
printf("Enter the price of %s cupcake: $", flavor);
scanf("%f", &price);
//determining if you have enough money for a second cupcake
if(price == maxPrice)
{
printf("\nOops! No more money left to spend on anymore cupcakes...enjoy the %s one! Bye!", flavor);
}
else if(price > maxPrice)
{
printf("\nWow, you overspent on that first cupcake...you owe $%.2lf. Bye!", fabs(newPrice)*1.0);
}
else
{
printf("Ok, looks like you you have $.2lf left to spend on cupcakes... Would you like to get another one?", maxPrice - price);
scanf("%s", &anotherCupcake);
if(anotherCupcake == "yes")
{
printf("Enter the flavor of cupcake 2: ");
scanf("%s", &flavor2);
printf("Enter the price of cupcake 2 $: ");
scanf("%f", &price2);
printf("Done! Enjoy your %s and %s cupcakes! Bye!", flavor, flavor2);
}
else
{
printf("Ok then...Enjoy that one %s cupcake! Bye!", flavor);
}
}
return 0;
}

You have to calculate newPrice with current values of
maxPrice-price, not at the beginning when neither maxPrice nor
price are initialized. Like that:
newPrice = maxPrice - price;
printf("\nWow, you overspent on that first cupcake...you owe $%.2lf. Bye!\n", fabs(newPrice)*1.0);
It'll work like that:
$ ./main
Please enter starting budget: 10
Enter the flavor of cupcake 1: 1
Enter the price of 1 cupcake: $18
Wow, you overspent on that first cupcake...you owe $8.00. Bye!
As a sidenote, you didn't specify what compiler you're using but the minimum set of flags you should use with gcc/clang is -Wall -Wextra -pedantic and fix all warnings.

Related

Why does it skip my command in C ? please check it

#include <stdio.h>
int main()
{
int inpa, med, oper, day, total;
char agree;
printf(" Bach Mai Hospital");
printf("\n\nHello, please enter your fee and we will calculate\npayment based on your insurance\n");
printf("How many days have you been in the hospital ");
scanf("%d", &day);
printf("How much is your medicine fee ");
scanf("%d", &med);
printf("Have you undergone surgery (Yes or No)");
scanf("%s", &agree);
switch(agree){
case 'Y':
printf("Enter your surgery fee ");
scanf(" %d", &oper);
break;
case 'N':
oper = 0;
break;
};
printf("%s", agree);
inpa = day * 15000;
printf("Your total fee\n");
printf("Inpatient fee: %-10d x 15000 = %d\n", day, inpa);
printf("Medicine fee: %-10d\n", med);
printf("Surgery fee: %-10d\n", oper);
total = inpa + med + oper;
printf("\n\nYou pay: %d\n", total);
return 0;
}
It skips my command from when I enter &oper
printf("Enter your surgery fee ");
scanf(" %d", &oper);
And it is the result
Bach Mai Hospital
Hello, please enter your fee and we will calculate
payment based on your insurance
How many days have you been in the hospital 8
How much is your medicine fee 90000000
Have you undergone surgery (Yes or No)Yes
Enter your surgery fee 80000000
PS D:\Desktop\Cprogram>
I would be so thankful if someone explain for me why
previously I have trouble with the "agree" variable which I declare a char but it understands "agree" as int. Thank you
printf("%s") expects a null character(\0). Whenever you want to print a character, you should use %c rather than %s.So replace printf("%s", agree); with print("%c",agree);, then everything works well.
printf("%s", agree);
This line seems to cause issue because:
agree is a char variable in stack and hold only 1 byte
When printf with %s, it is expected that you provide an char array end with value 0 which is string terminator.
Because of this when you call printf("%s", agree);, it will trigger a call to a string at address 'Y' or in hex value 0x59. And the access to this address is illegal and will cause undefined behavior for your program.

Issue With Nested If Statement

I was trying to ask the user if he/she wants another cupcake only if the cost of the first cupcake is less than their budget (maxPrice), but that does not work. It prints nothing after receiving user input. The error occurs where the program states: "if(anotherCupcake == "yes")" and it also occurs when it states, "anotherCupcake == "no".
Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main(int argc, char**argv)
{
float maxPrice;
char flavor[20];
char flavor2[20];
float price;
double price2;
char anotherCupcake[20];
double newPrice;
// int idxToDel = 2;
//memove(&word[idxToDel], &word[idxToDel + 1], strlen(word) - idxToDel);
printf("Please enter starting budget: ");
scanf("%f", &maxPrice);
printf("Enter the flavor of cupcake 1: ");
scanf("%s", &flavor);
printf("Enter the price of %s cupcake: $", flavor);
scanf("%f", &price);
//determining if you have enough money for a second cupcake
if(price == maxPrice)
{
printf("\nOops! No more money left to spend on anymore cupcakes...enjoy the %s one! Bye!", flavor);
}
else if(price > maxPrice)
{
newPrice=maxPrice-price;
printf("\nWow, you overspent on that first cupcake...you owe $%.2lf. Bye!", fabs(newPrice)*1.0);
}
else
{
printf("Ok, looks like you you have $%.2f left to spend on cupcakes... Would you like to get another one?", maxPrice - price);
scanf("%s", &anotherCupcake);
//figuring out what second cupcake you want
if(anotherCupcake == "yes")
{
printf("Enter the flavor of cupcake 2: ");
scanf("%s", &flavor2);
printf("Enter the price of cupcake 2 $: ");
scanf("%f", &price2);
printf("Done! Enjoy your %s and %s cupcakes! Bye!", flavor, flavor2);
}
if(anotherCupcake == "no")
{
printf("Ok then...Enjoy that one %s cupcake! Bye!", flavor);
}
}
return 0;
}
try use string compare to compare values of two string. It may work.
if(strcmp("yes", anotherCupcake) == 0)
{
printf("Enter the flavor of cupcake 2: ");
scanf("%s", &flavor2);
printf("Enter the price of cupcake 2 $: ");
scanf("%f", &price2);
printf("Done! Enjoy your %s and %s cupcakes! Bye!", flavor, flavor2);
}

Having issues with this simple program

The program is just simply supposed to calculate the users age by subtracting their dob from the current year. When I run the program it compiles successfully but I get a long number such as -215863352. The if and else conditions are added just to test them out, I was writing various programs using them to make sure I understand the syntax in c. I figure I'm missing something simple but can't figure it out.
#include <stdio.h>
int main()
{
int year;
int cyear;
int age = cyear - year;
printf("Please enter the year you were born: \n");
scanf("%i", &year);
printf("Now enter the current year: \n");
scanf("%i", &cyear);
if (1+1 == 2){
printf("You must be %i", age);
}
else {
printf("Cannot compute age, GOODBYE:\n");
}
return 0;
}
You are calculating the age before the input is taken from the user. So the age variable is storing a garbage value.
Solution:
Position the calculation of age after taking the input from user that is after taking input of cyear using scanf. The correct code is given below
#include <stdio.h>
int main()
{
int year;
int cyear;
int age =0; //initialise with 0
printf("Please enter the year you were born: \n");
scanf("%i", &year);
printf("Now enter the current year: \n");
scanf("%i", &cyear);
age = cyear - year; //note the change here
if (1+1 == 2){
printf("You must be %i", age);
}
else {
printf("Cannot compute age, GOODBYE:\n");
}
return 0;
}
enter code here
#include <stdio.h>
int main()
{
long long int year;
printf("Please enter the year you were born: \n");
scanf("%lld",&year);
long long int cyear;
printf("Now enter the current year: \n");
scanf("%lld",&cyear);
long long int age = cyear-year;
if (1){
printf("You must be %lld", age);
}
else { printf("Now enter the current year: \n");
scanf("%lld",&cyear);
printf("Cannot compute age, GOODBYE:\n");
}
return 0;
}

Inventory of a grocery store

I write a program to keep track of the inventory of a grocer store. But in my code i would like to print a value. And value is (Number of units) * (unit price). But somehow i get get the garbage value in my program. So Can you Please help me?
#include<stdio.h>
#include<conio.h>
#define MAX 5
int printinventory(int , int unit[] , float price[]);
int main()
{
int item[MAX],unit[MAX],x,i;
float price[MAX];
printf("Please enter how many category items (up to 5) : ");
scanf("%d",&x);
for(i=0;i<x;i++)
{
printf("\nPlease enter Number of Units #%d : ",i+1);
scanf(" %d",&unit[i]);
printf("\nPlease enter the Unit Price #%d : ",i+1);
scanf(" %f",&price[i]);
}
printinventory(x , unit , price);
getch();
}
int printinventory (int y, int unit[] , float price[])
{
int i,j=0;
float value[MAX];
for(i=0;i<y;i++);
{
value[i] = (unit[i] * price[i]);
}
system("cls");
printf("Item Number of Units Unit Price Value ");
printf("\n\n------------------------------------------------");
for(i=1;i<=y;i++)
{
printf("\n%d",i);
printf("\t %d",unit[j]);
printf("\t\t $%.2f",price[j]);
printf("\t$%.2f",value[j]);
j++;
}
printf("\n\n------------------------------------------------");
printf("\n\t\t\t\tTotal $ ");
getch();
}
The problem seems to be that you've mistakenly included a semicolon at the end of one of your for loops:
for(i=0;i<y;i++);

Variables retaining value after program is terminated, how to prevent? C

This is a program that asks the user to input Shipping information about selling bikes, pretty lame. At the end when it prints out the number of bikes order, and the total cost, the numbers get screwed up. The previously entered amounts seem to be sticking in the memory. How do I fix this? If that is not the problem I would not mind being told so :)
#include <stdio.h>
#include <math.h>
//structure
typedef struct
{char cust_name[25];
char add_one[20];
char add_two[20];
}ORDER;
ORDER order;
int main(void){
fflush(stdin);
system ( "clear" );
//initialize variables
double number_ordered = 0;
double price;
char bike;
char risky;
double m = 359.95;
double s = 279.95;
//inputs for order
printf("Enter Customer Information\n");
printf("Customer Name: ");
scanf(" %[^\n]s", &order.cust_name);
printf("\nEnter Street Address: ");
scanf(" %[^\n]s", &order.add_one);
printf("\nEnter City, State, and ZIP: ");
scanf(" %[^\n]s", &order.add_two);
printf("\nHow Many Bicycles Are Ordered: ");
scanf(" %d", &number_ordered);
printf("\nWhat Type Of Bike Is Ordered\n M Mountain Bike \n S Street Bike");
printf("\nChoose One (M or S): ");
scanf(" %c", &bike);
printf("\nIs The Customer Risky (Y/N): ");
scanf(" %c", &risky);
system ( "clear" );
//print order
printf("\n**********Shipping Instructions**********");
printf("\nTo: %s\n %s\n %s", order.cust_name, order.add_one, order.add_two);
if (bike == 'M' || bike == 'm')
printf("\n\nShip: %d Mountain Bikes", number_ordered);
else
printf("\n\nShip: %d Street Bikes", number_ordered);
if (bike == 'M' || bike == 'm')
price = number_ordered * m;
else
price = number_ordered * s;
if (risky == 'Y' || risky == 'y')
printf("\nBy Freight, COD %d\n", price);
else
printf("\nBy Freight, And Bill The Customer %d\n", price);
printf("*****************************************\n");
return 0;
}
You are printing number_ordered and price, which are doubles, using %d. %d is only for integer types. Use %lf to printf or scanf doubles.
The formats for both your scanf and your printf are wrong, so you're neither reading nor writing your values properly.

Resources