栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

7-12 实验2

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

7-12 实验2

已知两个整数x和y(x为任意整数,y为非负整数),利用循环结构计算x的y次幂并输出。假设x,y及x的y次幂不会超过int型范围。

输入格式:

只有一行,为两个用空格分隔的整数,依次代表x与y的值。

输出格式:

也只有一行,为一个整数,即x的y次幂的计算结果(测试数据中保证没有0的0次幂)。例如输出2的4次幂结果,即16。

样例">输入样例:
-7 5

输出样例:
-16807

代码如下:

#include
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

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 "> 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
1
2
3
4
5
6
7
8
9
10
11
#include       
#include        

int main ()
{
  printf ("7 ^ 3 = %fn", pow (7.0, 3.0) );
  printf ("4.73 ^ 12 = %fn", pow (4.73, 12.0) );
  printf ("32.01 ^ 1.54 = %fn", pow (32.01, 1.54) );
  return 0;
}

 Edit & Run



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

所以代码可以简化为:

#include
#include
int main()
{
	int x, y;
	scanf("%d %d", &x, &y);
	printf("%d", (int)pow(x, y));
return 0;

}

注意要强制类型转换,引用头文件!!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/699042.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号