This question already has answers here:
What is the behavior of integer division?
(6 answers)
Closed 10 months ago.
I am calculating salary by inflation
By random 1 to 5% the salary increase.
For exam, in 2020 inflation increased by 2%. And my salary is 1000.
Then answer should be 1000 * 1.02 = 1020.
So I made a simple code
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
srand((unsigned int)time(NULL));
int inc_rate = (rand() % 5) + 1;
float num = (100 + inc_rate) / 100;
printf("%d \n", inc_rate);
printf("%f", 100 * (float)num);
return 0;
}
But if I run it cannot count 1.02.
For example the outcomes
2
100.000000
How can I calculate division by C
The operator "/" performs integer division if both operands are integers (the fractional part is discarded). This means that the expression
(100 + inc_rate) / 100
will always be one if inc_rate is an integer between one and five.
Try this instead:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
srand(time(NULL));
int inc_rate = (rand() % 5) + 1;
float num = (100.0 + inc_rate) / 100.0;
printf("%d\n", inc_rate);
printf("%f\n", 100.0 * num);
return 0;
}
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
Consider the following C program :
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main()
{
srand(time(NULL));
for (int i = 0; i < 20; ++i) {
static float a = 0;
a = (rand() % 2001 - 1000) / 2.e3;
printf("%.4f ", a);
}
}
This will successfully generate then print a list of random number between -0.5 to 0.5. For example :
./main.out
-0.2475 -0.3640 -0.3945 0.2995 0.0460 0.2230 -0.0340 0.1630 -0.2275 -0.3450 0.3560 -0.4335 -0.0025 -0.2980 -0.0505 -0.1815 0.3115 -0.4465 -0.1325 -0.2340
I checked the Precedence of Operators and still don't understand how the expression (rand()%2001 - 1000)/2.e3 works.
(especially where does the negative sign comes from)
Let's analyze the expression (rand() % 2001 - 1000) / 2.e3:
the rand() function defined in <stdlib.h> returns a pseudo random integer of type int in the range 0 to RAND_MAX inclusively. RAND_MAX is a constant also defined in <stdlib.h> whose value is at least 32767.
rand() % 2001 computes the remainder of the division by 2001. Since rand() is positive, the result is a pseudo random number in the range 0 to 2000 inclusive, with a small bias caused by 2001 not dividing RAND_MAX evenly.
rand() % 2001 - 1000 is evaluated as (rand() % 2001) - 1000, the range of the result is shifted by 1000 toward the negatives, namely between -1000 and 1000 inclusively.
to evaluate (rand() % 2001 - 1000) / 2.e3, the value obtained from the previous steps is converted to type double and divided by 2.e3, which would be more readable as 2000.0. Hence the result is a floating point value of type double with 2001 possible distinct values between -0.5 and 0.5 inclusively.
a = (rand() % 2001 - 1000) / 2.e3; converts this double value to float, the type of a. The float value will be implicitly converted back to type double when passed to printf, this conversion does not produce exactly the same number in many cases.
note that there is no reason to define a as a static variable.
Here is an alternative implementation that produces more distinct values in the same inclusive range with a slightly less biased distribution:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
for (int i = 0; i < 20; ++i) {
double a = rand() / (double)RAND_MAX - 0.5;
printf("%f ", a);
}
printf("%\n");
return 0;
}
a = (rand() % 2001 - 1000) / 2.e3;
rand() is evaluated first
a = (rand() % 2001 - 1000) / 2.e3;
^^^^^^ int between `0` and `RAND_MAX` inclusive
Then the modulus operator generates a value between 0 and 2000.
a = ([0 .. 2000] - 1000) / 2.e3;
^^^^^^^^^^^ int
Then that value has 1000 subtracted, becoming a value between -1000 and 1000
a = ([-1000 .. 1000]) / 2.e3;
^^^^^^^^^^^^^^^ int
Then, divided by 2000.0 (or 2.e3) generates a double between -0.5 and 0.5
a = [-0.5 .. 0.5];
^^^^^^^^^^^^^ double
#include <stdio.h>
#include <math.h>
int main(){
int base5_v;
int digit = 0;
printf("> ");
scanf("%d", &base5_v);
int remainder = base5_v % 10;
base5_v /= 10;
int base10_v = remainder * (int) powf(5, digit++);
remainder = base5_v % 10;
base5_v /= 10;
base10_v += remainder * (int) powf(5, digit++);
remainder = base5_v % 10;
base10_v += remainder * (int) powf(5, digit++);
printf("%d in base 5 is %d in base 10\n", base5_v, base10_v);
return 0;
}
So I am having a hard time finding the issue in this code. the output is supposed to be like this after I input my number:
144 in base 5 is 49 in base 10
but when I compiled and ran the code it looked like this:
1 in base 5 is 49 in base 10
Can I get some help on what is wrong and how I can fix it?
Your code modifies base5_v each time it runs base5_v /= 10;.
In your example, you pass 144 as an input. The first time, it modified the value as 14 after the modulus operation, the second time 1 is left after modulus.
I think the biggest mistake in your code is not to use any loop. What'd happen if the user would enter 1234 or another digit length? There are many ways how you could have coded it, but this is one of them (ignoring the user input validation):
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#define MAX_DIGIT_LENGTH 10
int main()
{
char base5_v[MAX_DIGIT_LENGTH] = { '\0' };
printf("> ");
scanf("%s", base5_v);
int base10_v = 0;
int digit_length = (int)strlen(base5_v);
for (int digit = 0; digit < digit_length; digit++)
{
base10_v += pow(5, digit) * (base5_v[digit_length - digit - 1] - '0');
}
printf("%s in base 5 is %d in base 10\n", base5_v, base10_v);
return 0;
}
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;
}
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)));