1. 程式人生 > >C 求一個數的階乘問題

C 求一個數的階乘問題

問題

Write a program that reads a nonnegative integer, and computes and prints its factorial

(For example, 5! = 5x4x3x2x1 = 120)

#include<stdio.h>
#include<stdlib.h>

int main(void) {

	int num;
	int product=1;
	int j;
	printf("Enter a positive integer:");
	scanf_s("%d", &num);

	if (num <= 0) {

		while (num < 0) {
			printf("Enter a positive integer:");
			scanf_s("%d", &num);
		}
		
		while (num = 0) {
			printf("0! is 1");
			break;
		}
	}

	else {
		j = num;   //實現儲存num的原有值,不然會被下面的num=num-1改變

		while (num > 1) {
			product = product * num;
			num = num - 1;   //這一步最後的num=1,會導致最後的printf裡面的num輸出永遠是1!
		}
	}


	printf("%d! is %d", j, product);
	system("pause");
	return 0;
}