This question already has answers here:
Fast ceiling of an integer division in C / C++
(11 answers)
Closed 4 months ago.
I'm having trouble rounding up to the next integer, because of integer truncation. Basically, I want x/n (both integers) to be 9 but I keep getting 8. How do I divide two integers and get an integer that is the rounded up version of the actual decimal number? Simply using ceil(25.0/3.0) won't work for me, because in my actual program, x and n are integer values input by the user.
Also, why isn't the 3rd line I tried below able to run? Whenever I try to typecast inside the ceil function, I get a message saying "undefined reference to ceil."
int x = 25;
int n = 3;
int numOfStrings = ceil(((double)x) / n);
Floating point is always a problem.
It's simpler to just add the 0 ('false') or 1 ('true') of whether or not there is any remainder (modulo).
#include <stdio.h>
int main() {
int n = 3;
for( int x = 21; x < 30; x++ )
printf( "n:%d x:%d x/n:%d\n", n, x, x/n + !!(x%n) );
return 0;
}
n:3 x:21 x/n:7
n:3 x:22 x/n:8
n:3 x:23 x/n:8
n:3 x:24 x/n:8
n:3 x:25 x/n:9 // <=====
n:3 x:26 x/n:9
n:3 x:27 x/n:9
n:3 x:28 x/n:10
n:3 x:29 x/n:10
AND, you should be checking/preventing the possibility of division by zero (left as an exercise.)
Related
This question already has answers here:
Is floating point math broken?
(31 answers)
Why are floating point numbers inaccurate?
(5 answers)
Is floating-point == ever OK?
(14 answers)
Closed 11 months ago.
sample code is here, desire output is 2 ::
#include <stdio.h>
int main()
{
double i, a, b;
int j;
for (i = 0; i <= 3; i = i + .20)
{
if (i == 2)
{
printf("I=%lf\n", i);
}
}
}
When I use
#include <stdio.h>
int main()
{
double i, a, b;
int j;
for (i = 0; i <= 3; i = i + .25)
{
if (i == 2)
{
printf("I=%lf\n", i);
}
}
}
it works; but in the first case, it is not working. WHY ??
The short answer is that the use of a floating control variable for a for loop is unwise... comparing a floating value for equality is even less so.
Due to the storage of floating point numbers as a mantissa and an exponent, your 0.20000000 may well be 0.199999999...9 or 020000000...01 thus the comparison fails.
Typically, 0.25 and 2.000 will store exactly, as they are powers of 2. Hence a step of 0.25 works as anticipated.
MISRA C:2012 has Rule 14.1 to protect against using float or doubles as loop counters... and previously had a Rule to protect against testing float/double for equality -perhaps we should reinstate that Rule.
This question already has answers here:
How best to sum up lots of floating point numbers?
(5 answers)
Is floating point math broken?
(31 answers)
Closed 4 years ago.
Here I have a function sum() of type float that takes in a pointer t of type float and an integer size. It returns the sum of all the elements in the array. Then I create two arrays using that function. One that has the BIG value at the first index and one that has it at the last index. When I return the sums of each of those arrays I get different results. This is my code:
#include <stdlib.h>
#include <stdio.h>
#define N 1024
#define SMALL 1.0
#define BIG 100000000.0
float sum(float* t, int size) { // here I define the function sum()
float s = 0.0;
for (int i = 0; i < size; i++) {
s += t[i];
}
return s;
}
int main() {
float tab[N];
for (int i = 0; i < N; i++) {
tab[i] = SMALL;
}
tab[0] = BIG;
float sum1 = sum(tab, N); // initialize sum1 with the big value at index 0
printf("sum1 = %f\n", sum1);
tab[0] = SMALL;
tab[N-1] = BIG;
float sum2 = sum(tab, N); // initialize sum2 with the big value at last index
printf("sum2 = %f\n", sum2);
return 0;
}
After compiling the code and running it I get the following output:
Sum = 100000000.000000
Sum = 100001024.000000
Why do I get different results even though the arrays have the same elements ( but at different indexes ).
What you're experiencing is floating point imprecision. Here's a simple demonstration.
int main() {
float big = 100000000.0;
float small = 1.0;
printf("%f\n", big + small);
printf("%f\n", big + (19 *small));
return 0;
}
You'd expect 100000001.0 and 100000019.0.
$ ./test
100000000.000000
100000016.000000
Why'd that happen? Because computers don't store numbers like we do, floating point numbers doubly so. A float has a size of just 32 bits, but can store numbers up to about 3^38 rather than the just 2^31 a 32 bit integer can. And it can store decimal places. How? They cheat. What it really stores is the sign, an exponent, and a mantissa.
sign * 2^exponent * mantissa
The mantissa is what determines accuracy and there's only 24 bits in a float. So large numbers lose precision.
You can read about exactly how and play around with the representation.
To solve this either use a double which has greater precision, or use an accurate, but slower, arbitrary precision library such as GMP.
Why do I get different results even though the arrays have the same elements
In floating-point math, 100000000.0 + 1.0 equals 100000000.0 and not 100000001.0, but 100000000.0 + 1024.0 does equal 100001024.0. Given the value 100000000.0, the value 1.0 is too small to show up in the available bits used to represent 100000000.0.
So when you put 100000000.0 first, all the later + 1.0 operations have no effect.
When you put 100000000.0 last, though, all the previous 1000+ 1.0 + 1.0 + ... do add up to 1024.0, and 1024.0 is "big enough" to make a difference given the available precision of floating point math.
This question already has answers here:
Why dividing two integers doesn't get a float? [duplicate]
(7 answers)
Closed 5 years ago.
input example : 356
356/100, is suppused to be 3.56
But I'm getting 3.0000000000, I'm using ideone online compiler for C.
#include <stdio.h>
#include <math.h>
int main() {
int n;
double frac;
scanf("%d", &n);
frac = (n/100);
printf("%lf", frac);
return 0;
}
That's because here frac = (n/100); you are doing plain integer arithmetic (as n is declared as an int and 100 is interpreted as an int (any whole number is taken to be an int unless specified otherwise)). What you need to do is say explicitly that you want to do an arithmetic operation with digits after decimal point. One way is to use a cast: frac = ((double) n/100);
If you don't use the cast, the division will be performed as you expect, but then the digits after the decimal point will be dropped. Since frac is declared as a double, 0s would get tacked on to the end.
In C, the result of division of two integer numbers (e.g. int, short, long) is also an integer (it is counter-intuitive, but it is implemented this way for performance reasons). As a result, the result of 5/2 is 2 and not 2.5. This rule is only for integer numbers. So, if you need to get a floating-point result, at least one of the numbers in a division operation must be of a floating-point type.
In case of your code, if you use 100.0 instead of 100, you will get the desired result. Also you can use casts or define n as double.
This should work:
#include <stdio.h>
#include <math.h>
int main() {
int n; // You can define n as double but don't forget to modify scanf accordingly.
double frac;
scanf("%d", &n);
frac = (n/((double)100)); // Or, frac = (n/100.0)
printf("%lf", frac);
return 0;
}
You cannot call division using integers to be double without declaring it.
For example
int / int will result int.
Try declaring n as double
double n;
scanf("%lf", &n);
frag = n/100;
input data type is an integer.
just change it to double or float to fix this problem.
int main() {
double n;
double frac;
scanf("%d", &n);
frac = (n/100);
printf("%lf", frac);
return 0;
}
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 5 years ago.
I have read that floating numbers are stored as per IEEE 754 representation and sometimes approximate value is displayed if its not possible to represent the number.
I have written the following code in which i am extracting fractional part then multiplying it by 10 nine times inside the loop. At the end of the loop the value is 142000000.000000 (variable g).
I multiplied it again with 10 outside the loop and got the result as 1419999999.999999.
I stored the value which was calculated inside for loop explicitly in another variable(k) and multiplied it with 10 and got the result as 1420000000.000000
Can you please tell me why the difference how it is able to store the value correctly in the second instance (In variable k).
#include<stdio.h>
#include<math.h>
int main()
{
double f=3.142,g,i;
int j;
g=modf(f,&i);
printf("Inside loop");
for(j=1;j<=9;j++)
{
g = g * 10.0;
printf("\n%lf",g);
}
printf("\nLoop ends");
g = g * 10.0;
printf("\nThe value of g is %lf",g);
double k = 142000000.000000;
k = k * 10.0;
printf("\nThe value of k is %lf",k);
}
Output
Inside loop
1.420000
14.200000
142.000000
1420.000000
14200.000000
142000.000000
1420000.000000
14200000.000000
142000000.000000
Loop ends
The value of g is 1419999999.999999
The value of k is 1420000000.000000
The initial value of f is 3.142. This value can't be represented exactly, so any operations on this value will also result in an inexact value. That's why you eventually end up printing an inexact value.
In contrast, the initial value of k is 142000000.000000 which can be represented exactly as a double. Multiplying this value by 10 still gives a value that can be represented exactly.
This question already has answers here:
C program to convert Fahrenheit to Celsius always prints zero
(6 answers)
Closed 7 years ago.
I've written a code for the following program but the output seems to be wrong.
Question:
https://www.hackerrank.com/challenges/plus-minus
Code:
#include <stdio.h>
int main() {
int N,num,i,cp=0,cn=0,cz=0;
double fp,fn,fz;
scanf("%d",&N);
for(i=0;i<N;i++)
{
scanf("%d",&num);
if(num>0)
cp=cp+1;
else if(num==0)
cz=cz+1;
else
cn=cn+1;
}
fp=cp/N;
fn=cn/N;
fz=cz/N;
printf("%lf\n%lf\n%lf",fp,fn,fz);
return 0;
}
The Output comes as:
0.000000
0.000000
0.000000
Istructions:
fp=cp/N;
fn=cn/N;
fz=cz/N;
Are performed as integer division.
Change your code to:
fp=(double)(cp)/(double)(N);
fn=(double)(cn)/(double)(N);
fz=(double)(cz)/(double)(N);
you are doing an integer division which creates only integer results. If you want to calculate floating point results you need to perform floating point divisions.
int a = 1;
int b = 3;
int c = a / b;
// c is now 0 -> integer division
double i = 1.0;
double j = 3.0;
double k = i / j;
// k is now 0.3333333 -> floating point division
For correct result cast these expression's to double-
like this
fp=cp/N; // fp=(double)cp/N;
fn=cn/N; // fn=(double)cn/N;
fz=cz/N; // fz=(double)cz/N;
Working code
In previous case if cp(or cn or cz) is less than N then due to integer division you will get 0(fraction part will be discarded). Therefore m these casts .
Another method would be to use all variables as double .