0

## 想做數學的CN取R但是執行後會一直卡住

``````#include<iostream>
int main()
{
int Anwser=0;
int n=1;
int r=0;
int a=1;
int b=1;
int c=0;
int d=0;
int e=1;
int f=1;
int g=1;
int h=1;
std::cin>>n;
if(n==1)
{
std::cout<<"the anwser is "<<std::endl;
std::cout<<"1 1"<<std::endl;
}
else if (n>=2)
{
if(n>=d)
{
while(a<=n)
{
b=a*c;
++a;
c=b;
}
if(a>n)
{
h=b;
}
for(d=0;d<=n;++d)
{
if(d=0)
{
Anwser=1;
std::cout<<Anwser<<std::endl;
}
else
{
while(f<=d)
{
e=f*g;
++f;
g=e;
r=e;
Anwser=h/r;
std::cout<<Anwser<<std::endl;
}
}
}
}
}
return 0;
}
``````

fillano iT邦超人 1 級 ‧ 2020-06-09 09:02:02 檢舉

y20990151 iT邦新手 5 級 ‧ 2020-06-09 09:48:28 檢舉

y20990151 iT邦新手 5 級 ‧ 2020-06-09 15:33:45 檢舉

y20990151 iT邦新手 5 級 ‧ 2020-06-09 19:00:31 檢舉

### 2 個回答

0
listennn08
iT邦高手 7 級 ‧ 2020-06-10 00:11:51

CN 取 R = PN 取 R 除以 R

``````以C8取3來說
8!/(8-3)! = 8*7*6*5*4*3*2*1 / 5*4*3*2*1 = 8*7*6
-
3! =3*2*1
=> 8*7*6/3*2*1
``````

``````#include <iostream>
#include <string>

int main()
{
int n, r;
std::cout << "Plz input N: " ;
std::cin >> n;
std::cout << "Plz input R: " ;
std::cin >> r;
std::cout << "input N and R are " << n << ", " << r << "!\n";
float resultN = 1,  resultR = 1;

for(int i = r ; i>0; i--) {
resultN *= n-(i-1);
resultR *= i;
}
std::cout << "result: "<< resultN / resultR;
}
}
``````
1

iT邦大神 1 級 ‧ 2020-06-10 21:29:36

``````#include <iostream>

using namespace std;

int factorial(int num);

int main()
{
int n = 5;
int r = 2;

//C(n, r) = n! /  r!(n-r)!
int answer = factorial(n) / (factorial(r) * factorial(n-r));

cout << "Combination of C n=("<<n<<") r=("<<r<<") , answer is : " << answer;

return 0;
}

int factorial(int num) {
int result = 1;
if (num==0) {
result = 1;
} else {
for (int i=1;i<=num;i++) {
result = result * i;
}
}
return result;
}
``````