Not getting expected value when running a program [duplicate] - c

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.

Related

Does data types change the output of an operation in C [duplicate]

This question already has answers here:
What is the behavior of integer division?
(6 answers)
Closed last year.
Iam new to C programming and i guess this question might look foolish but I have searched and i didn't get a satisfactory answer:
My question is does hierachy of execution of operators depend on whether the declared variables are integer or float, here is a scenario which I don't understand;
this is the first case:
main()
{
int i=2,j=3,k;
k=i/j*j;
printf("%d",k);
and the output to that is 0 which i don't agree with;
But when I change the variables to float as in below;
main()
{
float i=2,j=3,k;
k=i/j*j;
printf("%f",k);
The output to becomes 2.00000
why is this?
In the first code snippet, the subexpression i/j has integer operands so integer division is performed. This means that the result is also an integer and any fractional part is truncated.
In the second snippet, both operands have floating point type so floating point division is performed.
and the output to that is 0 which i don't agree with;
The program is always right, people (programmers) do mistakes.
The operation below is an integer division and 2 divided by 3 is 0. Integer division does not round to the closest integer value which causes your confusuin.
i/j == 2/3 == 0
does hierachy of execution of operators depend on whether the declared variables are integer or float?
Hierarchy of execution as in order, no.
However, results very much depend on the types. Division involving two integers results in a truncated integer, so 2 / 3 is zero, not two thirds as you may expect.
Then, when you multiply that by two, you still have zero.
An example can be seen when calculating percentage of a ratio. Let's say 40 of the 60 students in a class are male. If you wanted to know the percentage of males, there's a vast difference between the two formulae below:
int males = 40;
int total = 60;
bad_pct = males / total * 100; // 40/60=0, 0*100=0.
good_pct = males * 100 / total; // 40*100=4000, 4000/60=66.
The issue of integer math vs. floating point math has been dealt with well already, but when you use the term "hierarchy of operators," I think you're referring to operator precedence.
No, it does not change this. Operator precedence is the same for floating point and integer math operations.

Division in C language [duplicate]

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

Why did my float get truncated? [duplicate]

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

number hold by double container is greater than float even if values are equal [duplicate]

This question already has answers here:
Floating point comparison [duplicate]
(5 answers)
Closed 9 years ago.
main()
{
float f=0.7;
if(0.7>f)
printf("Hi");
else
printf("Hello"):
}
When I compile this program output comes out to be Hi.
Can someone please explain the scenerio how 0.7>0.7 is true? Is this due to fact that 0.7 used in if statement is a double and f is a float?
Even if it is double still its value is 0.7 difference created is just that in case of double it is stored in 8 byte while in case of float it is stored in 4 byte. But I think it does not matters how big is your container when the value stored in container is equal. So 0.7 can never be greater than f. So according to me it should result in Hello. then why Hi is the output?
The container does makes the difference here. The idea is how these values are stored and then retrieved. If you use a number that can be converted back to exact decimal value. You may see the difference.
Use this and see the output:
float f=0.7f;
If you define float f = 0.7, it is stored as manttisa and exponent. It depends on the precision. So in this case .7 will be less than .7. If you define 0.7f it will be equal to 0.7.

float variables in C [duplicate]

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.

Resources