#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::cout<<"type your number"<<std::endl;
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;
}
我想要做數學的C N取R但是一直在執行時卡住,請問是哪裡出錯了嗎?
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;
}
}
我看了很久
實在看不懂你寫的程式
只好寫了另一個版本如下
#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;
}