林惜城


私信TA

用户名:reminder

访问量:27303

签 名:

等  级
排  名 94
经  验 8447
参赛次数 0
文章发表 95
年  龄 0
在职情况 学生
学  校 西安电子科技大学
专  业

  自我简介:

哈姆

TA的其他文章

题解 1105: 数列
浏览:562


解题思路:

(1)计算阶乘别用递归,除了装比没别的用处;

(2)计算n次幂要考虑0次幂的情况。

注意事项:

while (n--) 和 while (--n) 何时结束循环要分清。

参考代码:

#include #include #include using namespace std;

// 计算阶乘
double fact(int n) {
	double res = n;
	while (--n) {
		res *= n;
	}
	return res;
}
// 计算n次幂
double mypow(double x, int n) {
	double res = x;
	if (!n) {
		return 1; // 0次幂
	}
	while (--n) {
		res *= x;
	}
	return res;
}

int main() {
	double x = 0;
	int n = 0;
	cin >> x >> n; // 未对x非正数做异常处理,也通过了
	double res = 0;
	for (int i = 0; i < n; ++i) {
		res += (mypow(-1, i) * mypow(x, i + 1) / fact(i + 1));
	}
	cout << fixed << setprecision(4) << res << endl;
	return 0;
}


 

0.0分

1 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答

代码解释器

  评论区