Why does division result in zero instead of a decimal? - c

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.

Related

jeo=(1/(1+decade)); not giving me accurate answer

int decade;
float jeo;
PRINT("Enter Decade point =\r\n");
scanf("%d",&decade);
print_decimal(decade);
PRINT("\r\n");
jeo=(1/(1+decade));
PRINT("Decade point =");
print_decimal(jeo);//my function for showing floating point number.
PRINT("\r\n");
I have wrote this code in IAR embedded workbench software for ARM controller, but it's not giving me accurate answer, can anyone tell me why??
"when i am entering 3. it's giving me 0 answer".
You are just doing your calculation with integer and assign afterwards to a float value. This will remove the digits after the decimal point.
Try this:
jeo=(1.0/(1.0+decade));
You are assigning the result of an integer division to jeo. In this case, if decade is any integer other than 0, the result of integer division will be 0. (Note: If decade is -1, you will have undefined behavior as a result of division by 0)
When the type after usual arithmetic conversions is an integer type, the result is the algebraic quotient (not a fraction), rounded in implementation-defined direction (until C99)truncated towards zero (since C99)
So make either the numerator or the denominator a float.
jeo=((float)1/float(1+decade);
Try this
jeo=1/(1+float(decade));
this is because when trying to employ an integer in a logical expression like that, the result is calculated in integer first then converted to float. This procedure ,of course, removes the digits after the decimal point and adds artificial 0s.

Dividing a double number with a double of 0 gives the limit of the expression and not error

I've been asked the result of this code:
#include <stdio.h>
int main()
{
double a =0;
double b =2/ a;
printf("b=%f\n", b);
printf("SLABC\n");
return 0;
}
running it, the code prints b=inf and SLABC and then exists correctly.
I could not understand why the division of 2/0 does not rise an error (had it been int a=0, I'd get the appropriate runtime error), and my only assumption is that in type double, a=0 actually doesn't mean that a is 0, but rather that a is very close to 0 (and apparently, a>0 and not the negative, or it should have been -inf).
I get the same result even if a=0.0 and a=0.00000000. Feels to me like the computer has decided to calculate the limit of this expression (calculus style), but I suppose there is a more sensible explantation. Also, I'm not clear as to why its only positive, and not negative.
What you're seeing is proper floating point division.
The values infinity and negative infinity are valid floating point values, as well as "not-a-number".
When floating point division is done with a 0 divisor, the result will infinity with the sign matching the dividend.
If you were to calculate 0.0/0.0 or inf/inf, the result would be NaN, i.e. not-a-number.
C explicitly identifies this as undefined behavior (UB).
The result of the / operator is the quotient ... if the value of the second operand is zero, the behavior is undefined. C11dr §6.5.5 5
C does not define that the code should error.
Assigning a "value" of infinity with a sign that is the exclusive-or of the signs of finite operands is a common result.
This matches IEEE 754 behavior "The default result of divideByZero shall be an ∞ correctly signed according to the operation:" Adherence to IEEE 754 is not required by C, although many platforms strive for it.
In floats or doubles, division by zero is allowed and the result to that is +-INF or +-NAN.

Why do both % and fmod() exist in C

I took a quiz in my CS class today and got a question about the modulo operator wrong because I didn't know about the availability of % in C, I've been using fmod(). Why do both exist? Is one better/faster or do they just deal with different data types?
modulo division using % operator in C only works for integer operands and returns an integer remainder of the division.
The function fmod accepts double as arguments meaning that it accepts non-integer values and returns the remainder of the division.
Additional note on fmod: how is the remainder calculated in case of double operand? Thanks #chux for showing the documentation on how fmod calculates the remainder of a floating point division.
The floating-point remainder of the division operation x/y calculated
by this function is exactly the value x - n*y, where n is x/y with its
fractional part truncated.
The returned value has the same sign as x and is less or equal to y in
magnitude.
On the other hand, when the modulo division binary operator (%) was first designed, it was determined by the language designers that it would only support operands of 'integer' types because technically speaking, the notion of 'remainder' in mathematics only applies to integer divisions.
It's because % is an integer operator, and fmod stands for floatmod and is used for floating point numbers.
Why do both exist?
Because they may have computed different results, even with the same values. These differences may occur with negative values. In essence fmod() and % were different mathematical functions.
fmod(x,y), since C89, had the result "the result has the same sign as x and magnitude less than the magnitude of y".
i%j was not so singularly defined. See Remainder calculation for the modulo operation. This allow code to use existing variant processors effectively. The div() function was created to address this variability. Ref
By C99 they compute the same for the same values. Future C could allow 123.4 % 56.7
% is just integer modulo
fmod is float modulo and can be used as described in MSDN.
https://msdn.microsoft.com/en-us/library/20dckbeh.aspx

Cant figure out the way compiler does the calculation

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

Find the percentage that is one integer to another

I have two integers (amount of bytes of two files). One is always smaller if not the same than the other. I want to calculate the percentage that the smaller is of the bigger.
I'm using plain C. I've applied the math formula, but am getting always 0:
printf("%d\r", (current/total)*100);
Any ideas?
Try
printf("%g\r", (((double)current)/total)*100);
instead. Integer division always rounds towards zero. By converting one of the numbers to double first, you will trigger floating point division. If you would like to use integer arithmetic, you could also use
printf("%d\r", (100*current)/total);
which will print the percentage rounded down to the next integer.
Sven give you good advice.
If you want to keep your integers, do the multiplication before the division :
printf("%d\r", (current * 100) / total);
You will get a rounded result.
The integral division done with numerator < denominator always give 0. That's the explanation for your "always 0" problem. Multiplying by 100 before dividing get the integral part of your division (percentage)
my2c
I recommend scaling up the nominator before doing the division:
const float ratio = (100.f * current) / total;
Here, making the 100 a floating point literal will promote the calculation, so no explicit casts are necessary which is also a benefit.
Better to try:
printf("%lf\r", (((double)current)/total)*100);
Since answer will be in floating point.
Integer division rounds down, so if your answer is less than 1 you will get 0.
You could try something like this:
printf("%d\r", ((current*100)/total));
However you will always get an integer.
If you cast numerator to a float you will get float division and the right answer.
printf("%f\r", ((float)current/total * 100));
However you may want to truncate zeros after, for example, for 3 digits before the decimal and 2 after you can use:
printf("%3.2f\r", ((float)current/total * 100));
Check out:
http://www.cplusplus.com/reference/clibrary/cstdio/printf/

Resources