题目

2018-02-07  本文已影响0人  iamsea

Sum of the first nth term of Series

Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +...

#include <iomanip>

using namespace std;

string seriesSum(int n)
{
    double ret = 0.0;
    double base = 1.0;
    while (n--) {
      ret += 1 / base;
      base += 3;
    }
    stringstream retss;
    retss << setprecision(2) << fixed << ret;
    return retss.str();
}
std::string seriesSum(int n)
{
    float sum = 0;
    char str[3];
    for(auto i = 0; i < n; i++) sum += 1./(3*i+1);
    sprintf(str, "%.2f", sum);
    return str;
}
上一篇 下一篇

猜你喜欢

热点阅读