ゼロではない正の整数2個(n, r)を引数として与えられて,n個からr個を順に取り出す組み合わせの数(順列の数)を求める関数を作成し,それを利用して入力された2個の正整数の組から順列の数を求めるプログラムを作成したのですが、関数でint型を使った時とdouble型を使った時で答えが違っていました。僕は最初代入するのは整数だったので、int型でもオッケーだと思ったのでしたが、例えば、(20、5)や(99、3)を入れた時がダメでした。なぜでしょうか?
①正解を出せてるプログラム
#include <stdio.h>
int permutation (int n, int r)
{
double a, b, productn, productr, permutation;
productn = 1;
productr = 1;
permutation = 1;
for ( a = 1 ; a <= n ; a++ ){
productn *= a;
}
for ( b = 1 ; b <= n-r; b++){
productr *= b;
}
permutation = productn / productr;
return permutation;
}
int main(void)
{
int c, d;
scanf ("%d", &c);
scanf ("%d", &d);
printf("%d\n", permutation( c, d )); return 0;
}
②誤っているプログラム
#include <stdio.h>
int permutation (int n, int r)
{
int a, b, productn, productr, permutation;
productn = 1;
productr = 1;
permutation = 1;
for ( a = 1 ; a <= n ; a++ ){
productn *= a;
}
for ( b = 1 ; b <= n-r; b++){
productr *= b;
}
permutation = productn / productr;
return permutation;
}
int main(void)
{
int c, d;
scanf ("%d", &c);
scanf ("%d", &d);
printf("%d\n", permutation( c, d )); return 0;
}
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。