//Guys I have issues with my code and have been tearing my hair apart trying to resolve this. THe issue is that I am trying to validate my code so it doesn't calculate for negative numbers. If any one can help smooth up this program I would really appreciate it. Please.
//The objective of the tax calculator program will be to use C programming to calcualte sales tax for each of the Kudler Fine Food stores (DelMar, Encinitas and La Jolla)
//Standard input/output processing
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
//Starting point
int main ()
{
//Variables defined
//st = sales tax, tax rated = tr, pa = total purchase amount, sa = purchase amoount
float fstDelmar;
float ftrDelmar;
float fpaDelmar;
float fstEncinitas;
float ftrEncinitas;
float fpaEncinitas;
float fstLajolla;
float ftrLajolla;
float fpaLajolla;
float fsaPurchaseAmount;
int fStoreselect;
//Variable initializations for tax rates and purchase amount
ftrDelmar = .0725;
ftrEncinitas = .075;
ftrLajolla = .0775;
fsaPurchaseAmount = 0;
//Header & Introduction
printf("\n***********************************************************************");
printf("\n* Kudler Fine Foods *");
printf("\n* Sales Tax Calculator *");
printf("\n* Version 3.0 *");
printf("\n***********************************************************************\n");
//Ask user to select store.
printf ("\n STORE LOCATION \n");
printf ("\n 1) Del Mar \n");
printf ("\n 2) Encinitas \n");
printf ("\n 3) La Jolla \n");
printf ("\n Please select the store location (1-3): \n");
scanf ("%d", &fStoreselect);
//Validate store selection.
while (fStoreselect < 1 || fStoreselect > 3) {
fflush (fStoreselect);
printf ("INVALID SELECTION! Please select a valid location (1-3): \n");
scanf ("%d", &fStoreselect);
}
//Ask user to enter in total purchase amount.
printf ("\n What was your purchase amount? ");
scanf("$%f", &fsaPurchaseAmount); //user enters variable amount
//Validation to ensure that user's enter in purchase amounts using correct format.
while (fsaPurchaseAmount <= 0.0)
{
fflush(fsaPurchaseAmount);
printf("\n INVALID SELECTION! Please enter a valid purchase amount greater than zero.\n");
printf("\n The purchase amount is: $ ");
scanf("%f", &fsaPurchaseAmount);
}
//Calculation of sales tax in dollars for each of the store locations
fstDelmar = fsaPurchaseAmount * ftrDelmar;
fstEncinitas = fsaPurchaseAmount * ftrEncinitas;
fstLajolla = fsaPurchaseAmount * ftrLajolla;
//Calculation of total sales amount for each of the locations
fpaDelmar = fsaPurchaseAmount + fstDelmar;
fpaEncinitas = fsaPurchaseAmount + fstEncinitas;
fpaLajolla = fsaPurchaseAmount + fstLajolla;
//Displaying sales amount for purchase for each of the different locations
switch (fStoreselect) {
case 1:
//for Delmar location
printf("\n Purchase Amount Sales Tax Total Sales Amount ");
printf("\n _______________ _________ _________________ ");
printf("\n $%.2f $%.2f $%.2f",fsaPurchaseAmount, fstDelmar, fpaDelmar);
break;
case 2:
//for Encinitas location
printf("\n Purchase Amount Sales Tax Total Sales Amount ");
printf("\n _______________ _________ _________________ ");
printf("\n $%.2f $%.2f $%.2f",fsaPurchaseAmount, fstEncinitas, fpaEncinitas);
break;
case 3:
//for La Jolla location
printf("\n Purchase Amount Sales Tax Total Sales Amount ");
printf("\n _______________ _________ _________________ ");
printf("\n $%.2f $%.2f $%.2f",fsaPurchaseAmount, fstLajolla, fpaLajolla);
break;
}
printf("\n Hit the ENTER key to exit program\n");
//Pause the screen and wait for user to hit the ENTER key
getchar();
//EOF
}
This line has bug:
scanf("$%f", &fsaPurchaseAmount); //user enters variable amount
it supposed to be:
scanf("%f", &fsaPurchaseAmount); //user enters variable amount
Here are some observation about the code as presented:
Don't use floating point for money. It will only cause grief later. Ideally, take advice from an accounting professional. In the mean time, do arithmetic in cents, and scale to and from dollars for display.
Calculations like sales tax might be correctly done with a floating point multiply, but make sure you comply with the accepted practices for rounding back to whole cents. Again, seek advice from an accounting professional.
fflush() doesn't do what you think it does. For a file descriptor opened for writing (such as stdout) it guarantees that all output on that descriptor has been completed. It is used after printing a prompt and before calling something like scanf() to read the input. An example is: printf("What is your favorite color? "); fflush(stdout); fgets(color, sizeof(color), stdin);
Always check the return value of scanf(). It returns the number of conversions that succeeded. If it doesn't match the number of format specifiers, then only those that succeeded had values written to the named variables.
Be wary of literal characters other than whitespace appearing in a scanf() format string. These must be matched exactly by the input text, or the conversion fails. So a format like "$%f" is only matched by input that includes a literal dollar sign. This is probably not what your user expects. The format "%f" is easier on the user. If you want to allow an optional dollar sign, then scanf() may not be the best choice.
Related
I'm new to learning C, and practicing some basic code.
I keep getting either a 0 or a very large random number for the bill multiplication at the end. I think I've narrowed it down to an issue with my "quant" value but I can't figure it out. Here's the first part of the programme (that only calculates for the pizza options so far):
#include <stdio.h>
int main()
{
int num, cho, quant, bill;
printf("Select a number from the menu:\n1. Pizza\n2. Burger\n3. Sandwiches\n4.
Beverages \n");
scanf("%d",&num);
if(num==1)
{
printf("Select a number for the food you want to order, and the quantity. \n");
printf("1. Pepperoni\t\tRs 1000 \n2. Fajita\t\tRs 1000\n3. Hot n spicy\t\tRs 1100\n4.
Chicken Tikka\tRs 1200\n");
scanf("%d,%d",&cho,&quant);
{
if(cho==1)
cho=1000;
else if(cho==2)
cho=1000;
else if(cho==3)
cho=1100;
else if(cho==4)
cho=1200;
}
bill=cho*quant;
printf("Please take your food item(s). Total bill = Rs %d \nThank you.",bill);
}
getchar();
getchar();
getchar(); getchar(); getchar();
return 0;
}
The way you have your scanf for cho and quant right now expects the user to enter two numbers separated by nothing but a comma, i.e. 2,10. If you do that format of input, your code works fine. However, if this format is broken the scanf does not properly read in a number to one or both of your variables, and they are left unitialized with potentially garbage information in them (hence the really large random numbers you're seeing).
You should probably change that line to
scanf("%d%d",&cho,&quant)
I'm writing a code that allows the user to add employees by ID, age and salary however, for salary I'm not sure what value to use in order to scanf and printf a number such as 78950.86. I used double for SALARY because there are more values to hold and I've tried playing around with the printf and scanf for this variable, but it I either get segmentation faults or random numbers. Here's my code:
#include <stdio.h>
#define SIZE 2
// Define Number of Employees "SIZE" to be 2
struct Employee{
int ID;
int AGE;
double SALARY;
};
//Declare Struct Employee
/* main program */
int main(void) {
int option = 0;
int i;
struct Employee emp[SIZE];
printf("---=== EMPLOYEE DATA ===---\n\n");
// Declare a struct Employee array "emp" with SIZE elements
// and initialize all elements to zero
do {
// Print the option list
printf("1. Display Employee Information\n");
printf("2. Add Employee\n");
printf("0. Exit\n\n");
printf("Please select from the above options: ");
// Capture input to option variable
scanf("%d",&option);
printf("\n");
switch (option) {
case 0: // Exit the program
break;
case 1: // Display Employee Data
// #IN-LAB
printf("EMP ID EMP AGE EMP SALARY\n");
printf("====== ======= ==========\n");
//Use "%6d%9d%11.21f" formatting in a
//printf statement to display
//employee id, age and salary of
//all employees using a loop construct
for(i=0; i<SIZE; i++) {
printf("%d %d %11.2lf", emp[i].ID, emp[i].AGE, emp[i].SALARY);
}
//The loop construct will be run for SIZE times
//and will only display Employee data
//where the EmployeeID is > 0
break;
case 2: //Adding Employee
// #IN-LAB
printf("Adding Employee\n");
printf("===============\n");
for(i=0;i<SIZE;i++) {
printf("\nEnter employee ID: ");
scanf ("%d", &emp[i].ID);
printf("\nEnter employee Age: ");
scanf ("%d", &emp[i].AGE);
printf("\nEnter employee Salary: ");
scanf ("%11lf", &emp[i].SALARY);
}
//Check for limits on the array and add employee
//data accordingly
break;
default:
printf("ERROR: Incorrect Option: Try Again\n\n");
}
} while (option!= 0);
return 0;
}
Your format strings are using %ld.%02d when dealing with a double, which says to treat it as 2 integers separated by a period (which should have generated warnings). Fix the string to properly indicate one double, or if (as #MalcomMcLean suggests) you want to keep dollars and cents separately, use a different field/variable for each.
"I'm not sure what value to use in order to scanf and printf a number such as 78950.86."
Generally speaking, Salaries are not really "Large Numbers", in the world of Coding(or C data types, to be precise). For the example you have quoted even a single precision float data type will be sufficient. (Search for "max finite positive value in single precision" in the pagehttps://en.m.wikipedia.org/wiki/Single-precision_floating-point_format)
So the double data type you used is more than sufficient for the said purpose. As rightly pointed out by Scott, the segmentation faults are being caused because your format string suggests 2 data parameters, when there is only 1 double data type variable.
My opinion would be not to store salary data as separate dollars and cents. From the employer's perspective these cents are going to add up to dollars and they will eventually be merged with the dollar data, making your summation algorithm complicated.
In conclusion, you can use a double data type for salary variable. When printing salary, you can use "%.2f" in the format string. When using scanf to get salary in normal fixed point notation, you can use "%lf" in the format string.
I am trying to write a program in C to calculate the remaining balance after 1st, 2nd & 3rd monthly payments, given the loan, monthly payment amount, and interest rate. I am having a problem in entering the input (floating point numbers) i.e it only takes one input (loan) & displays the answer without considering the other 2 inputs (interest rate & monthly payments).
This problem occurs only when I use the floating-point numbers (even in other programs also). I want to ask if this is due to coding or due to any other reason.
My code is as follows:
#include<stdio.h>
main()
{
float loan,interest,monthly_payment;
float balance_Imonth,balance_IImonth,balance_IIImonth;
printf("Enter the amount of loan: ");
scanf("%.2f",&loan);
printf("Enter the amount of interest: ");
scanf("%.2f",&interest);
printf("Enter the amount of monthly payment: ");
scanf("%.2f",&monthly_payment);
balance_Imonth=((interest/(100*12))*loan)+(loan)-(monthly_payment);
balance_IImonth=((interest/(100*12))*loan)+(balance_Imonth)- (monthly_payment);
balance_IIImonth=((interest/(100*12))*loan)+(balance_IImonth)-(monthly_payment);
printf("Balance remaining after I payment: $%.2f\n",balance_Imonth);
printf("Balance remaining after II payment: $%.2f\n",balance_IImonth);
printf("Balance remaining after III payment: $%.2f\n",balance_IIImonth);
}
The format specification "%.2f" is OK for printf but not for scanf. Use just "%f".
In your program, all the scanf function calls fail. You are just seeing undefined behavior due to use of uninitialized variables.
Always check the return value of scanf to make sure that the operation succeeded before you proceed to use the variables in which scanf stores the results.
Use
if ( scanf("%f", &loan) != 1 )
{
// Deal with error.
}
I am trying to figure out why I can't get this to run properly. I just want four inputs from the user, and run the calculation at the end.
#include <stdio.h>
#include <math.h>
int main(){
double amount; /* amount on deposit */
double principal; /* what's the principal */
double rate; /* annual interest rate */
int year; /* year placeholder and no. of total years */
int yearNo;
printf("What is the principal? ");
scanf("%d", &principal);
printf("What is the rate (in decimal)? ");
scanf(" .2%d", &rate);
printf("What is the principal? ");
scanf(" %d", &principal);
printf("How many years? ");
scanf(" %d\n", yearNo);
printf("%4s%21s\n", "Year", "Amount on deposit");
/* calculate the amount on deposit for each of ten years */
for (year = 1; year <= yearNo; year++){
amount = principal * pow(1.0 + rate, year);
printf("%4d%21.2f\n", year, amount);
}
return 0;
}
It properly asks for the principal and rate, but then skips over the question about Principal and asks for years. Then it just sits there waiting for a "ghost" entry?
I've been reading that the scanf() adds some whitespace when hitting enter but thought the space before the %d would fix that?
I also saw you could add do { c=getchar(); } while ( c != '\n'); after each scanf but that seems to crash the program (I added int c = 0; to the beginning too).
Thanks for any help or ideas!
EDIT:
When I change the erroneous format specifier from:
scanf(" .2%d", &rate);
to:
scanf(" %d", &rate);
I then get a crash after entering my values.
.2%d is not a valid format string.
For a start, the % has to come first. In addition, if you're after a floating point value, d is not the right character - it's for integral values.
You should be using something like %f (you don't need width or precision modifiers).
On top of that, you've made a minor mistake of not using a pointer for one of your scanf calls:
scanf(" %d\n", yearNo);
That's probably going to cause a crash, and should be changed to:
scanf(" %d\n", &yearNo);
And, as a final suggestion, it's totally unnecessary to use whitespace before (or a newline after) %d or %f family of format specifiers. The scanner automatically skips whitespace before both of those.
So, the only two scanf format strings you need in this program are "%d" and "%lf" (f is for floats, lf is for doubles).
I am writing a program to work out who should pay what in the household, based upon their income. The desired behaviour is the following:
Print welcome message and ask how many people are in the household.
If the number entered is 10 or below, ask for their names.
Ask for each persons income. <- this is where the issue is
Display total income.
Calculate and display result.
Obviously this program is not complete and I need to stop the user entering negative values, but the biggest problem is that when the user enters each persons income, upon hitting the return key it does not ask for any more user input and the totalEarnings comes out as 0.
I am used to programming in C++ so I'm hoping I've just missed a quirk of C.
main.c
#include <stdio.h>
int main(void){
short numberOfPeople = 0;
char* names[10] = {0,0,0,0,0,0,0,0,0,0};
float earnings[10] = {0,0,0,0,0,0,0,0,0,0};
float totalEarnings = 0;
float bills = 0;
printf("Welcome!\nThis program calculates who should pay what for the bills in a proportional manner, based upon each persons income.\nHow many people are in your household?\n\n");
do {
printf("You can enter up to 10: ");
scanf("%d", &numberOfPeople);
} while(numberOfPeople > 10);
puts("");
for(short j = 0; j < numberOfPeople; ++j){
printf("What is person %d's name? ", j+1 );
scanf(" %s", &names[j]);
}
puts("");
for(short i = 0; i < numberOfPeople; ++i){
printf("How much did %s earn this month? ", &names[i]);
scanf(" %.2f", &earnings[i]);
totalEarnings += earnings[i];
}
printf("\nTotal earnings are %.2f.\n\n", &totalEarnings);
printf("How much are the shared bills in total? ");
scanf(" %.2f", &bills);
puts("");
for(short k = 0; k < numberOfPeople; ++k){
printf("%s should pay %.2f", &names[k], &bills);
}
puts("");
return 0;
}
You have not allocated any memory to hold the names so are scanf-ing them into null.
All bets are off after this point.
You have problems with extra & characters in the printf calls, which others have noted.
The problem you are reporting is likely caused by the line:
scanf(" %.2f", &earnings[i]);
The problem is that . in scanf formats has no defined meaning (it may be being ignored, or it may be causing the scanf call to fail.) The 2 limits the input to 2 characters, so will fail if anyone has an income with more than 2 digits. So you need to get rid of those and what you REALLY need is to CHECK THE RETURN VALUE of scanf to see if it is failing and do something appropriate if it is. Something like:
while (scanf("%f", &earnings[i]) != 1) {
scanf("%*[^\n]"); /* throw away the rest of the line */
printf("That doesn't look like a number, what did they earn this month? ");
}
Something similar should be done with all the other scanf calls.
As #LoztInSpace pointed out, names is not allocated.
And another mistake is you're using & operator with %s and %f specifiers in in your printf() calls. It won't give result as expected.
Also, is your intention really a loop to ask for "number of peoples"?