28.阶乘
一个正整数的阶乘是所有小于及等于该数的正整数的积,并且0的阶乘为1。自然数n的阶乘写作n!。 n!=1×2×3×…×n。阶乘亦可以递归方式定义:0!=1,n!=(n-1)!×n。
28.1 循环实现
(1)代码
#if 0
int main()
{
int n, i;
unsigned long long factorial = 1;
printf("输入一个整数: ");
scanf("%d",&n);
if (n < 0)
printf("Error! 负数没有阶乘");
else
{
for(i=1; i<=n; ++i)
{
factorial *= i;
}
printf("%d! = %llu", n, factorial);
}
system("pause");
return 0;
}
#endif
(2)运行结果
28.2 递归实现
(1)代码
#if 0
int main()
{
int n;
printf("输入一个整数: ");
scanf("%d", &n);
printf("%d! = %ld", n, multiplyNumbers(n));
system("pause");
return 0;
}
long int multiplyNumbers(int n)
{
if (n >= 1)
return n*multiplyNumbers(n-1);
else
return 1;
}
#endif
long int multiplyNumbers(int n);
(2)运行结果
29.循环输出26个字母(大写字母)
(1)代码
#if 0
int main()
{
char c;
for(c = 'A'; c <= 'Z'; ++c)
printf("%c ", c);
system("pause");
return 0;
}
#endif
(2)运行结果
30.输出大写或小写字母
(1)代码
#if 0
int main()
{
char c;
printf("输入u显示大写字母,输入l显示小写字母: ");
scanf("%c", &c);
if(c== 'U' || c== 'u')
{
for(c = 'A'; c <= 'Z'; ++c)
printf("%c ", c);
}
else if (c == 'L' || c == 'l')
{
for(c = 'a'; c <= 'z'; ++c)
printf("%c ", c);
}
else
printf("Error! 输入非法字符。");
system("pause");
return 0;
}
#endif
(2)运行结果
31.判断数字为几位数
(1)代码
#if 0
int main()
{
long long n;
int count = 0;
printf("输入整数n: ");
scanf("%lld", &n);
while(n != 0)
{
n /= 10;
++count;
}
printf("n 是 %d 位数。", count);
system("pause");
return 0;
}
#endif
(2)运行结果
32.计算一个数的 n 次方,例如: 23,其中 2为基数,3为指数。
32.1 while循环实现
(1)代码
#if 1
int main()
{
int base, exponent;
long long result = 1;
printf("基数: ");
scanf("%d", &base);
printf("指数: ");
scanf("%d", &exponent);
while (exponent != 0)
{
result *= base;
--exponent;
}
printf("结果:%lld", result);
system("pause");
return 0;
}
#endif
(2)运行结果
32.2 利用POW()库函数实现
(1)代码
#if 0
int main()
{
double base, exponent, result;
printf("基数: ");
scanf("%lf", &base);
printf("指数: ");
scanf("%lf", &exponent);
result = pow(base, exponent);
printf("%.1lf^%.1lf = %.2lf", base, exponent, result);
system("pause");
return 0;
}
#endif
(2)运行结果
32.3 递归实现
(1)代码
#if 0
int main()
{
int base, powerRaised, result;
printf("基数: ");
scanf("%d",&base);
printf("指数(正整数): ");
scanf("%d",&powerRaised);
result = my_power(base, powerRaised);
printf("%d^%d = %d", base, powerRaised, result);
system("pause");
return 0;
}
int my_power(int base, int powerRaised)
{
if (powerRaised != 0)
return (base*my_power(base, powerRaised-1));
else
return 1;
}
#endif
int my_power(int n1, int n2);
(2)运行结果
|