This question already has answers here:
Why does division result in zero instead of a decimal?
(5 answers)
Closed 8 years ago.
Im trying to sum the multiples of a number (x0) with a progression number (r) and a number of times (n). If I use the number x0 = 6, r = 3, n = 3, the result should be
6+9+12=27, but the program gives me always 18.
I try different times changing the formula but if I do on the paper the result is right, so Im afraid the problem can be the syntax...
So theres the program in C:
#include <stdio.h>
int sum_progression(int x0, int r, int n)
{
return (n/2) * ((2 * x0) + ((n - 1) * (r)));
}
void test_sum_progression(void)
{
int x0;
int r;
int n;
scanf("%d", &x0);
scanf("%d", &r);
scanf("%d", &n);
int z = sum_progression(x0,r,n);
printf("%d\n", z);
}
int main(void)
{
test_sum_progression();
return 0;
}
Thanks for helping!
When using ints with division the value is calculated and then truncated to int.
if you divide int by int you should do something like:
return (n/(double)2) * ((2 * x0) + ((n - 1) * (r)));
Related
This question already has answers here:
Division in c not giving expected value
(4 answers)
Closed 29 days ago.
I was making a code that adds a summation for a specific formula, but the sum is always 0 for some reason. What is the reason nothing is adding? I think maybe it is the declaration of int and double for the variables. When I do a simple equation, such as adding natural numbers, it works, but not for more complicated equations like the one below.
Code:
#include <stdio.h>
int main()
{
int i, n;
double sum = 0;
printf("Enter the max value for the sum: ");
scanf("%d", &n);
i = 1;
while(i <= n)
{
sum = sum + (1 / ((1 + i) * (1 + i)));
i++;
}
printf("Sum = %f\n", sum);
}
I tried the code pasted above, expected the correct sum, but resulted in only 0.0000.
In this statement
sum = sum + (1 / ((1 + i) * (1 + i)));
the sub-expression (1 / ((1 + i) * (1 + i))) uses the integer arithmetic. It means that if to divide 1 by any integer number greater than 1 the result will be equal to 0.
Consider this simple demonstration program
#include <stdio.h>
int main( void )
{
int i = 1;
i = i / 2;
printf( "i = %d\n", i );
}
Its output is
i = 0
You need to use the arithmetic with float numbers.
It will be enough to write
sum += 1.0 / ((1 + i) * (1 + i));
Or it will be even more better to write using long long int constant 1ll within the expression like
sum += 1.0 / ((1ll + i) * (1ll + i));
to avoid overflow for the integer multiplication.
Also as the range is specified as two positive numbers then it will be logically better to specify the variables i and n as having the type unsigned int.
You need to cast the result of the divison as a double since that is what you are expecting as a result. Int division will round it to closest whole number
This question already has answers here:
Why dividing two integers doesn't get a float? [duplicate]
(7 answers)
Why does division result in zero instead of a decimal?
(5 answers)
Dividing 1/n always returns 0.0 [duplicate]
(3 answers)
Closed 2 years ago.
I am trying to write a code that finds pi accurately. When I run my code I get an output of 1.000000 every time because n always equals 0 in the equation to find add and minus after the first equation but when I print it, n is increasing as it should. I don't get any error messages because there are no visible problems with the code that I have. This is a conversion from the same code I wrote in python and I don't know if that is meaning I have forgotten something.
#include <stdio.h>
int main()
{
int n = 1, iterations, times;
long double pi = 0.0, add, minus;
printf("Number of iterations: ");
scanf("%d", &iterations);
for (times = 1; times <= iterations; ++times)
{
add = 1 / n;
printf("%Lf \n", add);
pi = pi + add;
n = n + 2;
minus = 1 / n;
printf("%Lf \n", minus);
pi = pi - minus;
n = n + 2;
printf("%d \n", n);
printf("%Lf \n", pi);
}
pi *= 4;
printf("Pi = %Lf \n", pi);
return 0;
}
Works a treat if you define n as a double.
When n is defined as an integer 'minus = 1 / n;' will always be 0, except when n = 1;
This question already has answers here:
How to generate random float number in C
(6 answers)
Random float number generation
(14 answers)
Generate random between [0, 1)
(2 answers)
Closed 5 years ago.
I have found a code in this answer How to generate a random integer number from within a range a code that works perfectly, but tis is for integers. Does anybody know how can I change this code so it returns uniformly a number between 0 and 1?
#include <stdlib.h> // For random(), RAND_MAX
// Assumes 0 <= max <= RAND_MAX
// Returns in the closed interval [0, max]
long random_at_most(long max) {
unsigned long
// max <= RAND_MAX < ULONG_MAX, so this is okay.
num_bins = (unsigned long) max + 1,
num_rand = (unsigned long) RAND_MAX + 1,
bin_size = num_rand / num_bins,
defect = num_rand % num_bins;
long x;
do {
x = random();
}
// This is carefully written not to overflow
while (num_rand - defect <= (unsigned long)x);
// Truncated division is intentional
return x/bin_size;
}
You really don't need all that complicated code there. Imagining you initialized your pseudo-random number generator correctly in your main function, with for instance something like this for rand:
srand(time(NULL));
The following code should be enough:
double random(){
return (double)rand()/RAND_MAX;
}
The idea there is just to pick a random number between 0 and RAND_MAX, and then to divide it by RAND_MAX. As RAND_MAX/RAND_MAX is equal to 1, you will return a random value between 0 and 1.
The C way:
#include <stdlib.h>
int main(int argc, char** argv)
{
printf("Random value: %f\n", (float) rand() / (float) RAND_MAX);
return 0;
}
The C++11 way:
#include <random>
int main(int argc, char** argv)
{
std::default_random_engine generator;
std::uniform_real_distribution<float> distribution(0.0, 1.0);
printf("Random value: %f\n", distribution(generator));
return 0;
}
Is there any way to round systemGuess up. In this case the outcome of systemGuess is 5.5 I want it to be 6 how do I do this?
See code below:
int main(void){
int systemGuess = 0;
stystemGuess = (10 - 1)/2 + 1;
printf(" %d ", stystemmGuess);
}
Use floating point division and ceil:
stystemGuess = ceil((10 - 1)/2.0) + 1;
If you want to round 0.4 down, use round instead.
OP wants to perform an integer division with the result rounded-up.
// If the quotient fraction > 0, return next larger number.
unsigned udiv_ceiling(unsigned n, unsigned d) {
return (n + d - 1)/d;
}
// If the quotient fraction >= 0.5, return next larger number.
unsigned udiv_nearest_ties_up(unsigned n, unsigned d) {
return (n + d/2)/d;
}
stystemGuess = udiv_ceiling(10 - 1, 2) + 1;
// or
stystemGuess = udiv_nearest_ties_up(10 - 1, 2) + 1;
Additional code needed to handle negative numbers and in corner cases, protect against n + d - 1 overflow.
You can use
systemGuess = (10 - 1)/2.0 + 1 + 0.5;
The problem is that you do integer calculation.
So e.g. 9/2 is 4. If you use 9/2.0 you have floating point division, which gives you 4.5. Adding 0.5 in the end gives you 6.0 instead of 5.5, so when storing it in systemGuess, you get 6 instead of 5.
Integer division in C truncates toward 0, so if you do the math on the other side of 0 (i.e., on negative numbers), it will "round up". You might do this by subtracting an amount from the dividend and adding half that amount back to the result:
int main(void)
{
int systemGuess = 0;
//systemGuess = (10 - 1)/2 + 1;
systemGuess = (10 - 1 - 20)/2 + 1 + 10;
printf(" %d ", systemGuess);
}
Probably in your real program there is a more elegant way to make this happen.
Here you go:
#include <stdio.h>
#include <stdlib.h>
int divide(int x, int y);
int main(void){
int systemGuess = 0;
int x = 10-1;
int y = 2;
systemGuess = divide(x,y) + 1;
printf(" %d ", systemGuess);
}
int divide(int x, int y) {
int a = (x -1)/y +1;
return a;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to sum a large number of float number?
I have a matrix 'x' that is 10,000 elements by 10,000 elements.
In the first case I declare the matrix like:
int n = 10000;
unsigned int size_M = n*n;
unsigned int mem_size_M = sizeof(int)*size_M;
int* x = (int*)malloc(mem_size_M);
Step (1) The matrix is initialized:
for(i=0;i<n;i++)
for(j=0;j<n;j++)
x[i*n+j] = 1;
Step (2) Sum the elements of the matrix and print the total:
for(i=0i<n;i++)
for(j=0j<n;j++)
sum +=x[i*n+j];
printf("sum: %d \n", sum);
As I would expect the above code prints 'sum: 100000000 '.
However if I declare the matrix like:
int n = 10000;
float size_M = n * n;
float mem_size_M = sizeof(float) * size_M;
float* x = (float*)malloc(mem_size_M);
And again perform the steps 1 and 2 the correct answer is not printed out, but '16777216' instead. Why is this?
ANSWER: To get the appropriate answer do a type conversion...
sum +=(int)x[i*n+j];
This happens because of the precision limitations of the float type. You can't just add 1.0 to float with value > 16777216 (2^24), but you can add 2.0, or 0.1:
#include <stdio.h>
int main(void)
{
float f = 16777220;
printf("f = %f\n", f + 1);
printf("f = %f\n", f + 2);
printf("f = %f\n", f + 0.1);
return 0;
}
The IEEE-754 standard floating-point numbers have have 4 bytes, consisting of a sign bit, an 8-bit excess-127 binary exponent, and a 23-bit mantissa. It's a bit complicated to explain precisely why it happens, but I can say that this is a extreme case when operation error reaches its maximum.