/* *Copyright (c) 2014,烟台大学计算机学院 *All gight reserved. *文件名称:temp.cpp *作者:邵帅 *完成时间:2014年10月22日 *版本号:v1.0 * *问题描述:输出1/3-3/5+5/7-7/9...-19/21的结果 *输入描述:无 *程序输出;输出1/3-3/5+5/7-7/9...-19/21的值 */ #include<iostream> using namespace std; int main() { double sum, s, i; for (i = 1, s = 1; i < 20; i = i + 2, s = -s) sum = sum + s * (i / (i + 2)); cout << "sum=" << sum; return 0; }
运行结果:
知识点总结:最重要的是了解(-1)的处理方法,具体是在for语句中把s赋值为-s,这样,就可以得到一正一负的处理方法。
@ Mayuko