0
Follow
2
View

# Very simple computer secondary programming, why the results of the program will not output it

gyh33900 注册会员
2023-02-25 12:11

When calculating combination numbers, the use of integer variables may cause the result to overflow. Therefore, in this case, consider using long integers or floating-int variables.

In the given code, we use floating-point variables to calculate, but in the third loop, there is an error in the condition for calculating the factorial, which should be i > = h instead of k > = 1.

Therefore, the modified code looks like this:

``````
#include

float fun(int m, int n)
{
int i;
float j = 1, k = 1, h = 1;
float x;

for (i = m; i >= 1; i--)
j *= i;

for (i = n; i >= 1; i--)
k *= i;

for (i = m - n; i >= 1; i--)
h *= i;

x = j / (k * h);

return x;
}

int main()
{
int m = 12, n = 8;
float s = fun(m, n);
printf("%f", s);

return 0;
}

``````

In this code, we first use a loop to calculate m! n! And m minus n factorial. And then you divide them to get the number of combinations. Because floating point variables are used for computation, overflow problems of integer variables are avoided

dlstonefly 注册会员
2023-02-25 12:11

the reference answer GPT ᴼ ᴾ ᴱ ᴺ ᴬ ᴵ < br / > in your fun function, the third loop termination condition is not correct. It should be i >. = 1 instead of k > = 1. Therefore, when n > When m - n, the initial value of h is 0, causing the function to return a value of NaN, or "Not a Number", so your program has no output.

After modifying the terminating condition of the third loop in the fun function, your program should look like this:

``````#include

float fun(int m, int n) {
int i;
float j = 1, k = 1, h = 1;
float x;
for (i = m; i >= 1; i--)
j *= i;
for (i = n; i >= 1; i--)
k *= i;
for (i = m - n; i >= 1; i--)
h *= i;
x = j / (k * h);
return x;
}

int main() {
int m = 12, n = 8;
float s = fun(m, n);
printf("%f", s);
return 0;
}

``````

Then you can print the result correctly.

Publish Time
2023-02-25 12:11
Update Time
2023-02-25 12:11