This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
C - division doesnt work [duplicate]
(2 answers)
Closed 1 year ago.
Hello fellas hope you all doing well i am kinda newbie in C language, I just need to ask a basic question that is that when i divide numbers in C like this:
#include<stdio.h>
main()
{
float a = 15/4;
printf("%.2f", a);
}
the division happens but the answer comes in a form like 3.00(which is not correct it did'nt count the remainders)
But when i program it like this:
#include<stdio.h>
main()
{
float a = 15;
float b = 4;
float res = a/b;
printf("%.2f", res);
}
this method gives me the correct answer. So i want to ask the reason behind the difference b/w these two programs why doesn't the first method works and why the second method working?
In this expression
15/4
the both operands have integer types (more precisely the type int). So the integer arithmetic is performed.
If at least one operand had a floating point type (float or double) as for example
15/4.0
or
15/4.0f
then the result will be a floating point number (in the first expression of the type double and in the second expression of the type float)
And in this expression
a/b
the both operands have floating point types (the type float). So the result is also a floating point number.
When you state your varable to float you automatically casting the values he get from the equation.
For example:
Float a = 2/4 it's like writing float a = float(equation).
Take care,
Ori
Related
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 4 years ago.
I'm a Little confused about some numbers in C-Code. I have the following piece of Code
int k;
float a = 0.04f;
for (k=0; k*a < 0.12; k++) {
* do something *
}
in this case, what is the type of "0.12" ? double ? float ? it has never been declared anywhere. Anyways, in my program the Loop above is excuted 4 times, even though 3*0.04=0.12 < 0.12 is not true. Once I Exchange 0.12 with 0.12F (because I am globally restricted to float precision in all of the program), the Loop is now executed 3 times. I do not understand why, and what is happening here. Are there any proper Guidelines on how to write such statements to not get unexpected issues?
Another related issue is the following: in the Definition of variables, say
float b = 1/180 * 3.14159265359;
what exactly "is" "1" in this case ? and "180" ? Integers ? Are they converted to float numbers ? Is it okay to write it like that ? Or should it be "1.0f/180.0f*3.14159265359f;"
Last part of the question,
if i have a fuction
void testfunction(float a)
which does some things.
if I call the fuction with testfunction(40.0/6.0), how is that Division handled ? It seems that its calculated with double precision and then converted to a float. Why ?
That was a Long question, I hope someone can help me understand it.
...numbers that are not stored in a variable
They are called "constants".
Any unsuffixed floating point constant has type double.
Quoting C11, chapter §6.4.4.2
An unsuffixed floating constant has type double. If suffixed by the letter f or F, it has
type float. If suffixed by the letter l or L, it has type long double.
For Integer constants, the type will depend on the value.
Quoting C11, chapter §6.4.4.1,
The type of an integer constant is the first of the corresponding list in which its value can
be represented. [..]
and for unsuffixed decimal number, the list is
int
long int
long long int
Regarding the mathematical operation accuracy of floating point numbers, see this post
"0.12" is a constant, and yes, without a trailing f or F, it will be interpreted as a double.
That number can not be expressed exactly as a binary fraction. When you compare k * a, the result is a float because both operands are floats. The result is slightly less than 0.12, but when you compare against a double, it gets padded out with zeros to the required size, which increases the discrepancy. When you use a float constant, the result is not padded (cast), and by good luck, comes out exactly equal to the binary representation of "0.12f". This would likely not be the case for a more complicated operation.
if we use a fractional number for eg, like 3.4 it's default type if double. You should explicitly specify it like 3.4f if you want it to consider as single precision (float).
if you call the following function
int fun()
{
float a= 1.2f;
double b = 1.2;
return (a==b);
}
this will always return zero (false).because before making comparison the float type is converted to double (lower type to higher type) , At this time sometimes it can't reproduce exact 1.2, a slight variations in value can be happen after 6th position from decimal point. You can check the difference by the following print statement
printf("double: %0.9f \n float: %0.9f\n",1.2,1.2f);
It results ike
double: 1.200000000
float: 1.200000481
This question already has answers here:
C program to convert Fahrenheit to Celsius always prints zero
(6 answers)
Closed 5 years ago.
For a school assignment we are supposed to write a short piece of code that calculates the telescopic limit up to 100. The expect answer should be sum is: 0.99000
but my output is always sum is: 0.00000 no matter what I try.
I hope it is a quick fix that I have been overlooking, but I can't, for the life of me, figure out what it is.
here is my code below:
#include <stdio.h>
int main(){
float ans=0.0;
for(int i=1; i<100; i++){
ans += 1/ (i*(i+1));
}
printf("sum is: %.5f",ans);
return 0;
}
Have a look at the expression
1/ (i*(i+1))
i is of type int, and a 1 (digits) are by default of type int (integer constants of type int, to be pedantic).
So, all the participating members are of type int and the arithmetic will be integer arithmetic. It is not floating point arithmetic. Thus, for above expression, for any value of i, greater than 0, you'll have a result of 0 as an outcome of integer division.
You need to either
use a float or double type operand
cast one of the operands to float or double
to enforce a floating point arithmetic to get the desired result.
This question already has answers here:
C integer division and floor
(4 answers)
Closed 7 years ago.
#include <stdio.h>
int main(void)
{
float c =8/5;
printf("The Result: %f", c);
return 0;
}
The answer is 1.000000. Why isn't it 1.600000?
C is interpreting your 8/5 input as integers. With integers, C truncates it down to 1.
Change your code to 8.0/5.0. That way it knows you're working with real numbers, and it will store the result you're looking for.
The expression
8/5
is an all int expression. So, it evaluates to (int )1
The automatic conversion to float happens in the assignment.
If you convert to float before the divide, you will get the answer you seek:
(float )8/5
or just
8.0/5
When you don't specify what data types you use (for example, in your code you use the integer constants 8 and 5) C uses the smallest reasonable type. In your case, it assigned 8 and 5 the integer type, and because both operands to the division expression were integers, C produced an integer result. Integers don't have decimal points or fractional parts, so C truncates the result. This throws away the remainder of the division operation leaving you with 1 instead of 1.6.
Notice this happens even though you store the result in a float. This is because the expression is evaluated using integer types, then the result is stored as is.
There are at least two ways to fix this:
Cast the part of the expression to a double type or other type that can store fractional parts:
Here 8 is cast to the double type, so C will perform float division with the operands. Note that if you cast (8 / 5), integer division will be performed before the cast.
foo = (double) 8 / 5
Use a double as one of the operands:
foo = 8.0/5
This question already has answers here:
What decides what datatype that will be used to store the temporary value in?
(3 answers)
Closed 7 years ago.
int a=10;
float b;
printf("the no\n");
b=((10-1)/12)*50;
printf("b value is %f",b);
return 0;
But when I calculate the b value in scientific calc we get b=40. And my question is why it shows b=0 when I run my code
In the calculation, the expression ((10-1)/12) is a division of an integer by an integer. The first integer evaluates to 9, and since 9/12 is less than 1, 9/12 evaluates to 0. This 0 is then multiplied by 50 to give b = 0.
To make the division act like a float, make one of the constants in the division portion a float. You can do this several ways the shortest of which is to add "f" as a suffix to one of the numbers, e.g. use 10F instead of 10, to get ((10F-1)/12). This makes the subtraction a floating point operation, which make the division and then multiplication of your original expression floating point operations as well. This should then give you the expected (float) result.
There will be a loss of data when you try to perform integer division. As already explained,
b=((10-1)/12)*50;
will yield 0 because :
((10-1)/12)*50; = (9/12)*50; = (0)*50; = 0;
To prevent this data loss, you can do the following:
((10-1)/12.0)*50;
Basically, by 12.0, it will be read as a float, so appropriately, floating point division will be performed.
This question already has answers here:
Using %f to print an integer variable
(6 answers)
Closed 3 years ago.
May be this is a simple question but I am not sure about how float variables are stored in memory and why it is behaving in this way, can someone please explain about the following behavior.
#include<stdio.h>
int main ()
{
int a = 9/5;
printf("%f\n", a);
return 0;
}
Output:
0.000000
I have looked at some information on how float variables are stored in memory, it has stuff about mantissa, exponent and sign. But I am not getting how to relate that here.
int a = 9/5;
performs integer division and ignores the remainder, so a is set to 1. Attempting to print that using %f gives undefined behavior, but by chance you got 0.000000 out of it.
Do
double a = 9./5.;
instead, or print with %d if integer division was the desired behavior. (float would also work, but a will be promoted to double when passed to printf, so there's no reason not to use double.)
It is an Undefined Behaviour.
You are using float format specifier (%f) to print an int (a). You should use %d to see correct output.
It is an undefined behaviour in C. Use %d format specifier instead of %f.
Does printf() depend on order of format specifiers? gives you detailed answer.
Here's a brief analysis of your code:
int a = 9/5; // 9/5 = 1.8, but since you are doing integer division and storing the value in an integer it will store 1.
printf("%f\n", a);//Using incorrect format specifiers with respect to datatypes, will cause undefined behavior
printf("%d\n",a);//This should print 1. And correct.
Or if you want the float:
instead of int use float :
float a=9.0f/5;//This will store 1.800000f
//float a=9/5 will store 1.000000 not, 1.8 because of integer divison
printf("%f\n",a); //This will print 1.800000
Also do read this: http://en.wikipedia.org/wiki/IEEE_754-2008 on how floating points work.
Clarification about integer division:
C99:
6.5.5 Multiplicative operators
6 When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.88) If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a
88) This is often called ‘‘truncation toward zero’’.
Just assuming that your division should result in a fraction in normal math won't magically make it a float.
int a = 9/5;
You need to use
float a = 9.0/5;
First you need the right data type i.e. float (or better yet double for higher precision) to store a float.
Secondly, if you are dividing two integers i.e. 9 and 5, it will simply follow integer division i.e. only store the integer part of division and discard the rest. To avoid that i have added .0 after 9. This would force compiler to implicitly covert into float and do the division.
Regarding your mentioning of why it is printing 0, it is already mentioned that trying %f on integer is undefined behavior. Technically, a float is 4 bytes containing 3 byte number and 1 byte exponent and these are combined to generate the resultant value.