C++ 查找x项之前的系列和时出现意外错误

C++ 查找x项之前的系列和时出现意外错误,c++,math,sequence,C++,Math,Sequence,这是我要找到的系列(最多x个用户输入项): 以下是我编写的代码: int x; cout << "How many terms (x) you want to add the series till?\n\n "; cin >> x; float m, answer=0.0; for (int n=0; n<x; n++) { m=1/((2*n)+1); answer=answer+m; } cout << " \n The answer is

这是我要找到的系列(最多x个用户输入项):

以下是我编写的代码:

int x;
cout << "How many terms (x) you want to add the series till?\n\n ";
cin >> x;
float m, answer=0.0;
for (int n=0; n<x; n++)
{
  m=1/((2*n)+1);
  answer=answer+m;
}
cout << " \n The answer is " << answer;
intx;
cout>x;
浮点数m,答案=0.0;
对于(int n=0;n

m=1/((2*n)+1);
在右边做整数运算,因为所有涉及的值都是整数。对于n=0,你得到
1/((2*0)+1)=1/1=1
,而对于例如n=1,你得到
1/((2*1)+1)=1/3=0
,然后将其分配给浮点。最终,第一项为1,其余项为0,因此总和最终为1

如果将任何术语设为浮点型,如:

m = 1.0 / (2 * n + 1);
然后您将得到类似
1.0/3=0.333…
的结果

您可以在此处查看有关算术运算符规则的更多详细信息:


甚至更好(或更糟!),它只需要一段时间(
)要彻底改变这种行为:将
1
替换为
1.
,任何人都会在以后失去这段时间。当人们问C语言家族出了什么问题时,这些事情就是一个很好的例子。我会把它变成
1.0f
,因为
m
是一个
float
m = 1.0 / (2 * n + 1);