是什么导致我的c++代码出现错误

Whats causes bug in my c++ code?

本文关键字:错误 代码 c++ 我的 是什么      更新时间:2023-10-16

我试着写一个代码,它应该计算4-4/3+4/5-4/7+4/9+。。。但它一直打印"3"作为答案。

#include <iostream>
#include <math.h>
#include <conio.h>
using namespace std;
int main()
{
    int s=0,a,n;
    cin>>n;
    for(int i=0 ; i<=n ; i++)
    {
        a=(4/((2*i)+1))*pow(-1,i);
        s=s+a;
    }
    cout<<s;
    return 0;
}

您使用的是整数除法,因此级数收敛非常非常快。

sa设为doubles,并将4替换为4.0