漂亮的围嘴的视频教程:最简单的 IF 语句

来源:百度文库 编辑:高考问答 时间:2024/04/29 15:13:21
// 5!.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "stdio.h"

main()
{
int a;int j=1;int i=1;
printf("input the number:\n");
scanf("%d",&a);

if (i<=a)
{j=j*i; i++;}

printf("%d\n",j);
}
这是我在C++中编的程序,要求i的阶乘,但不对,请问是为什么

#include <stdio.h>

int main()
{
int a,j=1,i=1;
printf("input the number:\n");
scanf("%d",&a);

if (i<=a) //你这里,只进行一次判断,就结束了,if没有循环功能哦
{
j=j*i;
i++;
}

printf("%d\n",j);

return 0;
}

改成这样就OK了~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#include <stdio.h>

int main()
{
int a,j=1,i=1;
printf("input the number:\n");
scanf("%d",&a);

while (i<=a) //
{
j=j*i;//这句和下一句其实可以合起来写成j=j*i++;
i++;
}

printf("%d\n",j);

return 0;
}

阶乘 记得要循环的吧. 是不是 n * (n - 1) * (n-2) * 1?
那就是

变量 结果=1
i 从1->n循环
里面是
结果=结果 乘 i

改成
int a=1;
int i,j=1;
scanf("%d",&i);
while (a>i)
{j=j*a; a++;}
因为你要求的是i的阶成

你执行了一遍if块中的内容就过去了,这里应该用while