Telescopic limit output is different from expected output [duplicate] - c

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.

Related

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

How to print a double data type in C [duplicate]

This question already has answers here:
How to divide 2 int in c?
(5 answers)
C - double result returning the value of 0 [duplicate]
(2 answers)
Closed 4 years ago.
Why in C, when I print a double type variable with %f it shows 8.000000… but that is not the desire result . i want a result like 8.5000 how can i achieve this?
int main(){
int i, j;
double k;
i=8; j=9;
k = (i+j)/2;
printf("%f", k);
}
The problem is not with the format specifier, rather with the arithmatic operation.
By saying
k = (i+j)/2;
where, i and j and 2 - all are ints, you're doing integer division, and then, storing the result in a double. For integer division,
[..] When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded [...]
which is commonly known as "truncation towards zero". To avoid that from happenning, you need to enforce floating point arithmetic, by forcing or casting one of the operands to double (or float). Something like
k = ((double)i+j)/2;
or,
k = (i+j)/2.0; //2.0 is of type double
The point here is, if, in the operation, one of the operands is of the higher rank (double or float is higher ranked that int), all the operands will first be converted to the higher rank, and then the operation will be performed and the result will be of the type of the higher ranked type.
Since i and j are int the result is cast first to int. This looses precision. Explicitly cast to double k = (double)(i+j)/2
Comments are right. To better understand that: A C expression is evaluated in 'one chunk'. The right side of your assignment (i+j)/2 is a complete expression. Since it does only includes integer values, the arithmetic chosen will also be of integer type, (which leads to truncation of the result), creating temporary integer value (invisible to you), which is then assigned to a double.
You need to make at least one of the values in your expression a double (or float), then the compiler will promote all the arithmetic to floating point and the temporary value will also be of float type.
If you don't have a constant in your expression, you can also use casts:
((float)i+J)/2
It does not matter which of the 3 items get the cast, just one is enough.

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

Why does this C computation involving exponents produce the wrong answer? [duplicate]

This question already has answers here:
C program to convert Fahrenheit to Celsius always prints zero
(6 answers)
Closed 9 years ago.
I am trying to implement the below formula on C
Here is my code:
int function(int x){
return pow(10, (((x-1)/(253/3))-1));
}
int main(void){
int z = function(252);
printf("z: %d\n",z);
return 0;
}
it outputs 10. However a calculator outputs 94.6.
could anyone explain me what I am doing wrong?
Note that in this line
(((x-1)/(253/3))-1))
You are dividing the integer value x - 1 by an integer value 253 / 3. This will truncate the value to an int, meaning that you'll be raising an integer power to an integer power.
To fix this, try changing this expression to
(((x-1)/(253.0 / 3.0))-1))
This now will use doubles in the expression, giving you the value you want.
Hope this helps!
Adding to that, integers do not give you the decimal part of numbers, so a number like 3.5 will get cut down to 3 using integer. To fix this double is the way to go. In other words 3 is different than 3.0

Inconsistent results while printing float as integer [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
print the float value in integer in C language
I am trying out a rather simple code like this:
float a = 1.5;
printf("%d",a);
It prints out 0. However, for other values, like 1.4,1.21, etc, it is printing out a garbage value. Not only for 1.5, for 1.25, 1.5, 1.75, 1.3125 (in other words, decimal numbers which can be perfectly converted into binary form), it is printing 0. What is the reason behind this? I found a similar post here, and the first answer looks like an awesome answer, but I couldn't discern it. Can any body explain why is this happening? What has endian-ness got to do with t?
you're not casting the float, printf is just interpreting it as an integer which is why you're getting seemingly garbage values.
Edit:
Check this example C code, which shows how a double is stored in memory:
int main()
{
double a = 1.5;
unsigned char *p = &a;
int i;
for (i=0; i<sizeof(double); i++) {
printf("%.2x", *(p+i));
}
printf("\n");
return 0;
}
If you run that with 1.5 it prints
000000000000f83f
If you try it with 1.41 it prints
b81e85eb51b8f63f
So when printf interprets 1.5 as an int, it prints zero because the 4 LSBs are zeros and some other value when trying with 1.41.
That being said, it is an undefined behaviour and you should avoid it plus you won't always get the same result it depends on the machine and how the arguments are passed.
Note: the bytes are reversed because this is compiled on a little indian machine which means the least significant byte comes first.
You don't take care about argument promotions. Because printf is a variadic function, the arguments are promoted:
C11 (n1570), § 6.5.2.2 Function calls
arguments that have type float are promoted to double.
So printf tries to interpret your double variable as an integer type. It leads to an undefined behavior. Just add a cast:
double a = 1.5;
printf("%d", (int)a);
Mismatch of arguments in printf is undefined beahivour
either typecast a or use %f
use this way
printf("%d",(int)a);
or
printf("%f",a);
d stands for : decimal. so, nevertheless a is float/double/integer/char,.... when you use : "%d", C will print that number by decimal. So, if a is integer type (integer, long), no problem. If a is char : because char is a type of integer, so, C will print value of char in ASCII.
But, the problem appears, when a is float type (float/double), just because if a is float type, C will have special way to read this, but not by decimal way. So, you will have strange result.
Why has this strange result ?
I just give a short explanation : in computer, real number is presented by two part: exponent and a mantissa. If you say : this is a real number, C will know which is exponent, which is mantissa. But, because you say : hey, this is integer. no difference between exponent part and mantissa part -> strange result.
If you want understand exactly, how can know which integer will it print (and of course, you can guess that). You can visit this link : represent FLOAT number in memory in C
If you don't want to have this trange result, you can cast int to float, so, it will print the integer part of float number.
float a = 1.5;
printf("%d",(int)a);
Hope this help :)

Resources