nの階乗を求めるプログラム
Posted: 2008年12月01日(月) 10:28
キーボードから整数nを読み込み、
nの階上 n!=1×2×3×…n
を求めて表示させるプログラムを求めたいのですが、よくわかりません。
あと条件に0以下または13以上の場合は再入力するみたいです。
nの階上 n!=1×2×3×…n
を求めて表示させるプログラムを求めたいのですが、よくわかりません。
あと条件に0以下または13以上の場合は再入力するみたいです。
#include <stdio.h>
#include <stdlib.h>
#define ARRAY_SIZE 1000
#define SUPREMUM 10000
int main(void)
{
int i, j, n, x, amari, p = 0, sho = 0;
static int kekka[ARRAY_SIZE];
do
{
printf("0以上の数を入力:");
scanf("%d",&n);
}
while(n < 0);
kekka[0] = 1;
for(i = 0; i < n; i++)
{
for(j = 0; j <= p; j++)
{
x = kekka[j] * (i + 1) + sho;
sho = x / SUPREMUM;
amari = x % SUPREMUM;
kekka[j] = amari;
if(sho > 0 && p == j)
{
p++;
}
}
}
for(i = p, j = 1; i >= 0; i--,j++)
{
if(i == p)
{
printf("%4d",kekka);
}
else
{
printf("%04d",kekka);
if( (j % 10) == 0 )
{
printf("\n");
}
}
}
printf("\n");
return 0;
}#include <iostream>
#include <boost/static_assert.hpp>
template <int n>
struct factorial_helper
{
static const int value = n * factorial_helper<n - 1>::value;
};
template <>
struct factorial_helper<0>
{
static const int value = 1;
};
template <int n>
struct factorial
{
BOOST_STATIC_ASSERT(0 < n && n < 13);
static const int value = factorial_helper<n>::value;
};
int main()
{
const int n = /* ←に好きな整数をキーボードで入力すること! */;
std::cout << factorial<n>::value << std::endl;
return 0;
}
こんなことを書くとまた怒られそうですが...。-------------------------------------------------
#include<stdio.h>
int saiki(int n)/*再帰で階乗を求める*/
{
if(n > 0) return(n * saiki(n - 1));
else return(1);
}
int main(void)
{
int t;
scanf("%d",&t); /*値を入力する*/
printf("%d",saiki(t));/*値の階乗を表示*/
return(0);
}
----------------------------------------------------