scanf doesn't read double - c

I got problems regarding the minus operation in c.
printf("\nPlease enter your payment:\n", userpayment);
scanf("%.2f", &userpayment);
customerchange = userpayment - totalfinal;
printf("The amount of change is %.2f\n", customerchange);
I declared userpayment and totalfinal as double.
Whenever I input the price for example; userpayment = 2000 and the totalfinal is 1500, the output will always be 1500.
What is the solution to this?
This is the output:
Enter the Price of Item:
500
Enter Quantity of Item:
3
The total amount of Payment is: RM1500.00
Is this the last item?
y
Rm50 cash rebate has been given to the customer.
Total Payment before cash rebate is: 1500
Total Payment after cash rebate is 1450
Please enter your payment:
5000
Your change is RM-14500.00

If "userpayment" is defined as a double, then change
scanf("%.2f", &userpayment);
to
scanf("%lf", &userpayment);
or change your variables to floats instead.
As it stands, you're scanning a float into the memory of a double, resulting in unpredictable behavior.

You have an incorrect format specifier in scanf. Read the documentation.
http://www.cplusplus.com/reference/cstdio/scanf/
You should also check the return value of scanf to ensure that it was able to parse what you expected it to parse.
Also, if you had read your compiler warnings you could have saved yourself the trouble of asking this question.

You are confusing the format from printf, it is similar but not the same, try just replacing %.2f to %lf

Since you defined your variable as double you should use:
scanf("%lf", &userpayment);
The f is for float values, lf (long float) for doubles.

Related

Calculating percentages in C

I am trying to find out how percentages are calculated within C, and specifically I am trying to find out how much taxes you get from user input, if the tax would be 21%.
But after trying the code in the terminal with input : 130,
which means I want 21% of 130$, it gives me a negative value of -858993459
How do Ifix this or where did I go wrong?
All of my google searches come up empty too, but probably because I am not using the correct phrasing so all info is welcome.
#include <stdio.h>
double get_tax_amount(double price_including_taxes)
{
return price_including_taxes *0.21;
}
int main()
{
printf("What was your price? ");
double price;
scanf("%d", &price);
printf("The tax price is: %d", get_tax_amount (price));
}
You’re using the wrong conversion specifier in both scanf and printf. To read a double value with scanf you need to use %lf and to print a double value with printf you need to use %f.
Because of how those functions work, they don’t know the number, type, or order of arguments you’ve actually passed to them - they just see a sludge of bytes on the stack or a sea of argument registers. The only way for them to know what arguments they should expect is through what you specify in the format string.
%d is used to read and print int types, %c for individual characters, %s for strings, etc.
Try "%lf" instead of "%d". "%d" is expecting an integer, which conflicts with variable type "double".
The variable type double should use %lf in scanf function, and %f in printf function.

For loop ignoring first line, after first loop execution in C

I am trying to store some products in an array and further, I will insert a new product to this array or I will delete an existing from this array. It is my plan, and I am trying something like bellow.
When looping, first loop executed successfully, but from second loop only showing Enter product name, but scanf("%s", p[i].pname) not giving me to insert the value. Would someone help me to solve this!!
#include <stdio.h>
struct product{
char pname[30];
int quantity;
float cost;
};
/*void insertnew();
void delete();*/
void main()
{
struct product p[50];
int i;
for(i = 0; i < 3; i++){
printf("Enter Product Name:\n");
scanf("%s", p[i].pname);
printf("Enter Quantity:\n");
scanf("%d", &p[i].quantity);
printf("Enter Cost:\n");
scanf("%.2f", &p[i].cost);
printf("*****************\n");
}
for(i = 0; i < 3; i++){
printf("Name    = %s\n",p[i].pname);
printf("Quantity = %d\n",p[i].quantity);
printf("Cost = %.2f\n",p[i].cost);
printf("-----------\n");
}
}
/*void insertnew(){}
void insertnew(){}*/
It will be more helpful for me if insertnew() and delete(), what am I going to do, is the right way?
Output:
The problem is here, when you're attempting to read in a float:
scanf("%.2f", &p[i].cost);
Format specifiers for scanf, unlike those for printf, do not take a precision specifier. This means the . character is invalid as part of a format string.
If you compile with warnings enabled (-Wall -Wextra on gcc) it will warn you of this:
x1.c:20:8: warning: unknown conversion type character ‘.’ in format [-Wformat=]
scanf("%.2f", &p[i].cost);
^
This results in nothing being read in when you input a value for this field, and the given textis left in the input buffer. When the next scanf executes expecting a string, it reads what is already in the buffer without prompting.
The correct way to handle this (at least for a float) is to remove any kind of length specifier:
scanf("%f", &p[i].cost);
If the user enters any more significant digits, you won't see them when you print with %.2f.
When I tried to compile your code with gcc, I got a warning:
prod.c:20:8: warning: unknown conversion type character ‘.’
in format [-Wformat=]
scanf("%.2f", &p[i].cost);
This drew my attention to the spurious "." in the scanf argument. Once I removed it, it compiled without warnings, and your code scanned all three items for me and printed them correctly.
Note however, that while the above will get the simple case to work, you need to perform input validation testing the return values of scanf() and retrying or aborting the input in case of failure - depending on what you intended to do in case of invalid input. Or - to be more robust - as was suggested in a comment by Weather Vane, read the input into a string with fgets() and then try to parse it with sscanf().
Overall, scanf() is not a good fit if the input can contain invalid entries - you should build some custom solution instead.
cost expect to store a type float. So scan a float.
(then it can be displayed with any format)
scanf("%f", &p[i].cost);
then it works:
Enter Product Name:
boxa
Enter Quantity:
10
Enter Cost:
11.5
*****************
Enter Product Name:
boxb
Enter Quantity:
4
Enter Cost:
12.4
*****************
Enter Product Name:
boxc
Enter Quantity:
122
Enter Cost:
3.3
*****************
Name = boxa
Quantity = 10
Cost = 11.50
-----------
Name = boxb
Quantity = 4
Cost = 12.40
-----------
Name = boxc
Quantity = 122
Cost = 3.30
-----------
You can't do
scanf("%.2f",&p[i].cost);
Scanf doesn't accept the formatted float value. You can only change it while printing the value. change that line to
scanf("%f",&p[i].cost)
Everything else seems fine.

to calculate remaining loan balance

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.
}

Simple C program not calculating correctly

So, I'm completely new to programming, and I'm learning to program C. I'm trying to write a simple program in C to calculate commission as follows
#include<stdio.h>
int main()
{
float fRate, fSales_Price, fCost, fCommission;
printf("\nEnter your commission rate: ");
scanf("%.2f",&fRate);
printf("\nEnter the price of the item sold: ");
scanf("%.2f", &fSales_Price);
printf("\nEnter the original cost of the item: ");
scanf("%.2f", &fCost);
fCommission = (fRate / 100) * (fSales_Price - fCost);
printf("\nYour commission is: %.2f", fCommission);
}
Whenever I try to run it, two things happen. First, if I try to enter any decimals into the program, e.g. if I said the rate was 12.5, it immediately skips the other inputs and completes the program, saying commission is 0.00. If I ignore decimals, the program runs fine until the end, when I still get commission as 0.00. Any suggestions?
Your format specifier is wrong, you must use compiler warnings if you do, then you wouldn't be asking this, because that format specifier is invalid, you cannot limit the number of decimal places with scanf() it's been discussed in many questions on SO, more importantly you don't need to, and it wouldn't be meaningful, so just remove the .2 from your format specifier, and instead, check that scanf() succeeded before using the values.
"%.2f" is an illegal format string for scanf, so your code causes undefined behaviour. The correct format string is "%f".
Also you should check the result of scanf. If scanf fails, the bad data is not consumed from the input and so subsequent scanfs fail too (this is why you see the other inputs skipped).
For example:
if ( 1 != scanf("%f", &fRate) )
{
printf("Invalid input for fRate.\n");
exit(EXIT_FAILURE);
}
"%.2f" is not a valid format for scanf. See scanf() manual page for details.
The easiest format to use is "%f".
Also, it's a good practice to check the return value of scanf so you know when the operation was successful.
if ( scanf("%f", &fRate) != 1 )
{
// Error reading the data.
// Deal with the error.
}

Finding Mean value program. Variable declaration and inputs

The program always prompts me to give one more input, if I declare 3 vars asks 4 inputs etc... The catch here is that if i put another variable inside the program, it always prompts me to input one more from the number i declared at the first place.
It DOES show the average correctly, but always asks me to give one more input which i think program doesnt even count and probably its the last input it asks me, but its there!
//Variable declaration.
int math,pro,net;
int average;
//ask user to give 3 grades.
printf("Give me your grades from your last semester\n");
//prompt user.
scanf("%d\n %d\n %d\n",&math,&pro,&net);
// simple average.
average = (math+pro+net)/3;
// show average.
printf("Your average is :%d\n\n",average);
change
scanf("%d\n %d\n %d\n",&math,&pro,&net);
to
scanf("%d %d %d",&math,&pro,&net);
however, the real problem was the last newline character in your scanf format. scanf would keep on eating up whitespace character and won't terminate. however, if you send to stdin an EOF sign (hit ctrl+d on linux) the average will be computed with 3 variables specified.
note that newlines are treated by scanf same as other whitespace characters.
Its because extra "\n" at the end of the scanf function. You can either Do the following code:
scanf("%d %d %d",&math,&pro,&net);
or if you want to follow your coding standard then write:
scanf("%d\n %d\n %d",&math,&pro,&net);
Also note that your calculation is in itegers. If your grades are in the continental range (i.e. 1..5) you probably want to float average = (math+pro+net)/3.; printf("Your average is :%f\n\n",average); to avoid the loss of the fractional part od the result.

Resources