I'm struggling in letting the program read the variable total that was previously input after asking for the input for the variable month. The total is always 28257 and I don't know why.
I found out using " %c" on line 11 works, but I would like to know why "%s" doesn't.
#include <stdio.h>
int main(void) {
int total;
char month;
float sales;
printf ("Enter total amount collected (-1 to quit): ");
scanf("%d", &total);
printf("Enter name of month: ");
scanf("%s", &month);
printf("total collections : $ %d\n", total);
sales = (total/1.09);
printf("sales : $ %.2f\n", sales);
printf("county sales tax: $ %.2f\n", sales * 0.05);
printf("state tax: $ %.2f\n", sales*0.04);
printf("total sales tax collected: $ %.2f\n", sales *0.05 + sales *0.04);
return 0; }
you declared month as character, so you should use %c for input. %s is used for input character array. and before scanf("%c", &month);, also use getchar();.
getchar();
scanf("%c", &month);
Related
#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.
#include <stdio.h>
int main()
{
int comp,loop=1,tcomp=0;
char cont;
char name[50];
float donate=0,total,gtotal;
printf("\nGot representative? [Y to continue]: ");
scanf("%s", &cont);
while(cont=='y'){
printf("\nRepresentative name : ");
scanf("%s", &name);
printf("How many companies? : ");
scanf("%d", &comp);
tcomp+=comp;
do{
printf("Enter amount of donation : ");
scanf("%f", &donate); loop++;
total+=donate;}
while(loop<=comp);
printf("%s : %.2f\n", name, total);
printf("\nGot representative? [Y to continue]: ");
scanf("%s", &cont);}
printf("\nTotal Representative : %d", tcomp);
gtotal+=total;
printf("\nTotal Donations : %.2f\n", gtotal);
}
Current output :
Got representative? [Y to continue]: y
Representative name : ABC
How many companies? : 3
Enter amount of donation : 1
Enter amount of donation : 2
Enter amount of donation : 3
ABC : 6.00
Got representative? [Y to continue]: y
Representative name : ZXC
How many companies? : 3
Enter amount of donation : 1
ZXC : 7.00
As you can see here, the 2nd loop did not reset and it's summing the numbers of first loop. How do I rectify this? How do I make it that the loop starts fresh each time? p/s : I was asked specifically to use while and do while loop.
Below your corrected code.
int main()
{
int comp,loop=1,tcomp=0;
char cont;
char name[50];
float donate=0,total=0,gtotal=0;
printf("\nGot representative? [Y to continue]: ");
scanf("%c", &cont);
while(cont=='y')
{
printf("\nRepresentative name : ");
scanf("%s", name);
printf("How many companies? : ");
scanf("%d", &comp);
tcomp+=comp;
loop=0;
total=0;
do
{
printf("Enter amount of donation : ");
scanf("%f", &donate); loop++;
total+=donate;
}
while(loop<comp);
printf("%s : %.2f\n", name, total);
printf("\nGot representative? [Y to continue]: ");
scanf("%c", &cont);
gtotal+=total;
}
printf("\nTotal Representative : %d", tcomp);
printf("\nTotal Donations : %.2f\n", gtotal);
return 0;
}
As you can see:
You must reset loop variable before each loop where amount are asked.
You must reset total before that loop
You must save to gtotal for each iteration of first while loop.
You must use %c instead of %s to get a single char: scanf("%c", &cont);
I'm having trouble figuring out why my float variable keeps printing out 0 when I input it as a number.
Code:
int num, month, day, year;
float price[10000];
printf("Enter item number: \n");
scanf("%d", &num);
printf("Enter unit price: \n");
scanf("%f", &price);
printf("Enter purchase date (mm/dd/yyyy): \n");
scanf("%d/%d/%d", &month, &day, &year);
printf("Item\t\tUnit\t\tPurchase\n");
printf(" \t\tPrice\t\tDate\n");
printf("%d ", num);
printf("$%.2f ", price);
printf(" %d/%d/%d\n", month, day, year);
return 0;
I input 555 for my item number, 13.5 for my price, and 10/24/2010 for my date.
When I did this it printed out that my price was $0.00. It does this for any number I input. Why?
You can not insert array value like this -
scanf("%f", &price);
Use a for loop to insert values into the array price -
for(i=0; i<sizeWhatYouWant; i++){
scanf("%f", &price[i]);
}
Or just change the declaration float price[10000] to -
float price;
Just change this:
float price[10000];
to this:
float price;
Because you use it as a single variable and not as an array
There are two things to notice.
change float price[10000]; to float price; as you'll be using only a single float variable, so you don't need an array.
You need to check the return value of scanf() to ensure proper input.
Also, as a note, you might want to initialize the local variables, as they are not automatically initialized.
You have declared price as an array you need to do it this way
int num, month, day, year;
float price[10000];
printf("Enter item number: \n");
scanf("%d", &num);
printf("Enter unit price: \n");
scanf("%f", &price[0]); /* <---- it's not &price it's &price[0] */
printf("Enter purchase date (mm/dd/yyyy): \n");
scanf("%d/%d/%d", &month, &day, &year);
printf("Item\t\tUnit\t\tPurchase\n");
printf(" \t\tPrice\t\tDate\n");
printf("%d ", num);
printf("$%.2f ", price[0]); /* <---- it's not price it's price[0] */
printf(" %d/%d/%d\n", month, day, year);
return 0;
you have to store the value in the first element of the array, and then print the first element too, i.e. price[0].
If you just want to read a single value, then you don't need to declare price as an array, so this would be the solution
int num, month, day, year;
float price/* [10000] it doesn't need to be an array */;
printf("Enter item number: \n");
scanf("%d", &num);
printf("Enter unit price: \n");
scanf("%f", &price);
printf("Enter purchase date (mm/dd/yyyy): \n");
scanf("%d/%d/%d", &month, &day, &year);
printf("Item\t\tUnit\t\tPurchase\n");
printf(" \t\tPrice\t\tDate\n");
printf("%d ", num);
printf("$%.2f ", price);
printf(" %d/%d/%d\n", month, day, year);
return 0;
You was printing the address to the first element of the array instead of the value at that address, and it was being converted to unsigned int or unsigned long int, so when you used the "%f" specifier, it was printing 0.
In both cases:
To prevent this kind of mistake, you should turn your compilers warnings ON, if using gcc
gcc -Wall -Wextra -Werror ${SOURCE_FILES} -o ${OUTPUT_FILE}
would do it.
And also, on invalid input, your program will have undefined behavior, you need to check that scanf() did actually read the value you instructed it to read, that is achieved by checking the return value from scanf() which equals the number of matched items, in your case
if (scanf("%d", num) != 1)
errorInputWasInvalid();
since you are requesting 1 item, then scanf() has to return 1.
Here is my code:
#include <stdio.h>
float calculateBalance(float payment, float balance, float rate);
int main(void){
float loanAmount, interestRate, monthlyPayment;
printf("Enter amount of loan:");
scanf("%.2f", &loanAmount);
printf("\nEnter interest rate:");
scanf("%.1f", &interestRate);
printf("\nEnter monthly payment:");
scanf("%.2f", &monthlyPayment);
loanAmount = calculateBalance(monthlyPayment, loanAmount, interestRate);
printf("Balance remaining after first payment: %.2f\n", loanAmount);
loanAmount = calculateBalance(monthlyPayment, loanAmount, interestRate);
printf("Balance remaining after second payment: %.2f\n", loanAmount);
loanAmount = calculateBalance(monthlyPayment, loanAmount, interestRate);
printf("Balance remaining after third payment: %.2f\n", loanAmount);
}
float calculateBalance(float payment, float balance, float rate){
return (balance-payment + balance*rate);
}
I am trying to calculate the balance after three payments are made; However, when I try and run the code in terminal, it's not letting me input anything, and instead is just reading in random numbers and then calculating the balance after three payments(I want to be able to input things, but it isn't allowing me to). How do I fix this?
The issue is in the fmt string itself. As #T.C. said in a comment
try using
scanf("%f", &var);
instead. If there are only 2 dec values, then it will only read that.
You can try a adding a getc(stdin); after each scanf.
I'm writing a program that basically just takes a bunch of user input and Outputs it in the form of a check. My problem is that I'm entering 2 sentences and while the second one is fine it completly skips the first one! and the user last name is working but the first name just outputs "z" it is the weirdest thing and my teachers philosophy is figure it out yourself. So can anyone possibly help me?? Here is my code...
#include<stdio.h>
#include<string.h>
int main()
{
char date[8];
int checkNum;
char payeeFirst[10];
char payeeLast[10];
double amount;
char memo[50];
char wordAmount[100];
printf("Please enter the date: ");
scanf("%s", &date);
printf("Please enter the check number: ");
scanf("%d", &checkNum);
printf("Please enter the payee First name: ");
scanf("%s", &payeeFirst);
printf("Please enter payee last name: ");
scanf("%s", &payeeLast);
printf("Please enter amount: ");
scanf("%d", &amount);
printf("Please enter amount in words: ");
fgets (wordAmount, sizeof(wordAmount)-1, stdin);
printf("Please enter memo: ");
fgets (memo, sizeof(memo)-1, stdin);
printf(" \n");
printf("Date: %s .\n", date);
printf("Check Number: %d .\n", checkNum);
printf("Payee: [%s] [%s] .\n", payeeFirst, payeeLast);
printf("Amount: %d .\n", amount);
printf(" Check %d \n", checkNum);
printf(" Date: %s \n", date);
printf("Pay to the\n");
printf("Order of %s %s $%d \n", payeeFirst, payeeLast, amount);
printf("%s", wordAmount);
printf(" \n");
printf(" \n");
printf("Memo: %s \n", memo);
return 0;
}
Your scanf calls all leave the '\n' in the stream (the next scanf will ignore it though).
The first fgets reads an empty string (well ... a string containing a single '\n').
Try reading the numbers with fgets too (to a temporary buffer) and sscanf from the buffer to the correct variable. This way all the '\n' will be accounted for.