Cant figure out the way compiler does the calculation - c

Given is a C code, in which i am trying to figure out how the calculation order would go, well i thought it should be 3/2 first and then *5 or the other way round. But it gives an unexpected output of
5.000000
#include <stdio.h>
int main(void) {
// your code goes here
float a = 3/2*5;
printf("%f", a);
return 0;
}

This is expected.
It calcuates 3/2 first (as integer), which is truncated down to 1. Then it multiplies by 5.
Try casting the numbers to (float) in your calculation - then you'll get the expected answer.
As suggested by damienfrancois, you can also get the compiler to treat them as floating point numbers as follows:
float a = 3.0/2.0*5;
In general, if you don't give any indication otherwise (such as the .0, or a cast), the compiler will treat numbers as an integer

The line
float a = 3/2*5;
computes a as the integer division of 3 by 2, which is 1, then multiplied by 5 and cast to float.
Replace it with
double a = 3.0/2.0*5;
or
float a = 3.0f/2.0f*5;
and you'll get 7.500000

It divides the integer 3 by integer 2, then multiplicates by integer 5, and then converts to a float.
Try float a = 3.f/2*5;

The multiplication and division operator have equal precedence in evaluation. Since both operators are left to right associative, integer division (3/2) is performed first resulting in 1 and then followed by multiplication with 5. Readup on operator associativity in C language
http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence

Related

C don't get the right result

I need the result of this variable in a program, but I don't understand why I can't get the right result.
double r = pow((3/2), 2) * 0.0001;
printf("%f", r);
The problem is integer division, where the fractional part (remainder) is discarded
Try:
double r = pow((3.0/2.0), 2) * 0.0001;
The first argument of the pow() expects a double. Because the ratio: 3/2 uses integer values, the result passed to the argument is 1. By changing to float values, the result of the division can retain the fractional part, and the result becomes 1.5, the form expected by the function.
(3/2) involves two integers, so it's integer division, with the result 1. What you want is floating point (double) division, so coerce the division to use doubles by writing it as (3.0/2.0)

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

Time = distance over speed in C

I'm trying to find the time taken to travel over an inputted distance going at a constant speed in C. The code I have functions but the output is printed as 0? Any idea what is going wrong?
#include <stdio.h>
#include <stdlib.h>
int main() {
int distance, speed = 80;
float time;
// This is how to read an int value
printf("Please enter a distance in kilometers to be covered at 80KPH. \n");
scanf("%d", & distance);
printf("You typed: %d\n", distance);
printf("\n");
time = distance / speed;
printf("It will take you %.2f to cover ", time);
}
Because the two operands are integers, the compiler generates code for integer division. But you want real division. So cast one or more of the operands to a floating point type and the compiler will emit code for real division.
time = (float) distance / time;
Integer division is what you learnt in elementary school. So, 11/3 is 3 remainder 2, for example. In C the expression 11/3 evaluates to 3. This is integer division. In your case it seems that the numerator (distance) is less than the denominator (time) and so the expression
distance / time
evaluates to 0.
This is a common confusion caused by the overloading of the division operator. This operator means integer division if both operands are integers, otherwise it is real division.
The key point to learn is that it is the types of the operands that determine whether integer or real division is used. The type of the variable in which the result is stored has no influence on this choice.
Change
time = distance / speed;
to
time = (float) distance / speed;
You were doing an integer division instead of a floating point division.
Once you changed the code according to what the others said (cast to float or double first), you will also need to change the format specifier from "%d" to "%f" for displaying floating point numbers (be it float or double), or else you will see garbage in your output.
EDIT: Sorry for mixing this up. I was thinking of a fix where you define speed and distance as float instead of int. In that case, you can simply convert "int" to "float" and "%d" to "%f" (possibly with accuracy and/or rounding flags). However, this will change the way the program works (because the user can now enter non-integral values), so it might not be what you want.

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.

Why does division result in zero instead of a decimal?

Teaching myself C and finding that when I do an equation for a temp conversion it won't work unless I change the fraction to a decimal. ie,
tempC=(.555*(tempF-32)) will work but tempC=((5/9)*(tempF-32)) won't work.
Why?
According to the book "C Primer Plus" it should work as I'm using floats for both tempC and tempF.
It looks like you have integer division in the second case:
tempC=((5/9)*(tempF-32))
The 5 / 9 will get truncated to zero.
To fix that, you need to make one of them a floating-point type:
tempC=((5./9.)*(tempF-32))
When you do 5/9, 5 and 9 are both integers and integer division happens. The result of integer division is an integer and it is the quotient of the two operands. So, the quotient in case of 5/9 is 0 and since you multiply by 0, tempC comes out to be 0. In order to not have integer division, atleast one of the two operands must be float.
E.g. if you use 5.0/9 or 5/9.0 or 5.0/9.0, it will work as expected.
5/9 is an integer division not a floating point division. That's why you are getting wrong result.
Make 5 or 9 floating point variable and you will get correct answer.
Like 5.0/9 OR 5/9.0
5/9 is an integer expression, as such it gets truncated to 0. your compiler should warn you about this, else you should look into enabling warnings.
If you put 5/9 in parenthesis, this will be calculated first, and since those are two integers, it will be done by integer division and the result will be 0, before the rest of the expression is evaluated.
You can rearrange your expression so that the conversion to float occurs first:
tempC=((5/9)*(tempF-32)); → tempC=(5*(tempF-32))/9;
or of course, as the others say, use floating point constants.

Resources