已知两个整数x和y(x为任意整数,y为非负整数),利用循环结构计算x的y次幂并输出。假设x,y及x的y次幂不会超过int型范围。
输入格式:
只有一行,为两个用空格分隔的整数,依次代表x与y的值。
输出格式:
也只有一行,为一个整数,即x的y次幂的计算结果(测试数据中保证没有0的0次幂)。例如输出2的4次幂结果,即16。
样例">输入样例:
-7 5
输出样例:
-16807
代码如下:
#include<stdio.h>
int main()
{
int x, y,xh=1;
scanf("%d %d", &x, &y);
//计算x的y次幂并输出
for (; y > 0; y--)
xh = xh * x;
printf("%d", xh);
return 0;
}
本题考查基本的for循环的应用
下面介绍C语言中的次方(幂次)的函数:
function
<cmath> <ctgmath>
pow
- C90
- C99
- C++98
- C++11
double pow (double base, double exponent);
Raise to power
Returns base raised to the power exponent:
baseexponent
- C99
- C++98
- C++11
Header <tgmath.h> provides a type-generic macro version of this function.
Parameters
base
Base value.
exponent
Exponent value.
Return Value
The result of raising base to the power exponent.
If the base is finite negative and the exponent is finite but not an integer value, it causes a domain error.
If both base and exponent are zero, it may also cause a domain error on certain implementations.
If base is zero and exponent is negative, it may cause a domain error or a pole error (or none, depending on the library implementation).
The function may also cause a range error if the result is too great or too small to be represented by a value of the return type.
- C90 (C++98)
- C99 (C++11)
If a domain error occurs, the global variable errno is set to EDOM.
If a pole or range error occurs, the global variable errno is set ERANGE.
Example
| |
Output:
7 ^ 3 = 343.000000 4.73 ^ 12 = 125410439.217423 32.01 ^ 1.54 = 208.036691 |
大家估计没兴趣认真看,做一个总结
1,函数名:POW
double pow (double base, double exponent);
返回值为double类型
2,作用:求幂次
pow(A,B) 就是A的B次方
3, 头文件:#include<math.h>
所以代码可以简化为:
#include<stdio.h>
#include<math.h>
int main()
{
int x, y;
scanf("%d %d", &x, &y);
printf("%d", (int)pow(x, y));
return 0;
}
注意要强制类型转换,引用头文件!!