0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C言語学習 - 階乗

Last updated at Posted at 2022-08-02

この記事について

・C言語の勉強を始めた。
・ソース以外に残すことに興味を持った。
・Qiitaはよく見るので、どーせならと

今日のソース

入力した整数の階乗を計算する。
階乗より非負整数であるため、1 ~ n について考える。
ただし、0!=1 と定義する。
負の数が入力された場合は、とりあえず、1を出力にした。
本来は入力されても、非負整数を再入力させるような処理が必要。

#include <stdio.h>

int n = 0;
int factorial = 1;

int main(void)
{
	printf("入力した数字:");
	scanf("%d",&n);
	
	if(n >= 0){
		for(int i=1; i < n; i++){
    			factorial = factorial * i;
    		}
		
	}else{
        		factorial = 1;
	}
	
	printf("factorial = %d\n",factorial);
	return 0;
}

実行結果

入力した数字:5
factorial = 24

やってみて思ったこと

初めてでも簡単に投稿できた。
これなら続けられそう。
Arduinoとかも載せてみようかな。

修正(8/3に追記)

ありがたいことに、実行結果について間違いを指摘いただけました!
間違っていた理由としては、forループの条件を間違えたことで入力回数分動作していなかったから。

修正前
		for(int i=1; i < n; i++){
    			factorial = factorial * i;
修正後
		for(int i=1; i <= n; i++){
    			factorial = factorial * i;

実行結果

入力した数字:5
factorial = 120

修正して思ったこと

指摘して頂けなかったら、修正しないままだったと思う。
恥ずかしい記事を残すことにならずに済んだので、非常にありがたいと感じた。
時たま、自分の記事を見直すようにする。

0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?