用 C++ 计算总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9134928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculating a Sum with C++
提问by Stripers247
I wrote the following code to sum the series (-1)^i*(i/(i+1))
. But when I run it I get -1
for any value of n.
我编写了以下代码来总结系列(-1)^i*(i/(i+1))
。但是当我运行它时,我会得到-1
任何 n 值。
Can some one please point out what I am doing wrong? Thank you in advance!
有人可以指出我做错了什么吗?先感谢您!
#include <iostream>
using namespace std;
int main()
{
int sum = 0;
int i = 1.0;
int n = 5.0;
for(i=1;i<=n;i++)
sum = (-1)^i*(i/(i+1));
cout << "Sum" <<" = "<< sum << endl;
return 0;
}
回答by Mysticial
Problem #1:The C++ ^
operator isn't the math power operator. It's a bitwise XOR.
问题#1:C++^
运算符不是数学幂运算符。这是一个按位异或。
You should use pow()
instead.
你应该pow()
改用。
Problem #2:You are storing floating-point types into an integer type. So the following will result in integer division (truncated division):
问题#2:您将浮点类型存储为整数类型。所以以下将导致整数除法(截断除法):
i/(i+1)
Problem #3:You are not actually summing anything up:
问题 3:你实际上并没有总结任何东西:
sum = ...
should be:
应该:
sum += ...
A corrected version of the code is as follows:
代码的更正版本如下:
double sum = 0;
int i = 1;
int n = 5;
for(i = 1; i <= n; i++)
sum += pow(-1.,(double)i) * ((double)i / (i + 1));
Although you really don't need to use pow
in this case. A simple test for odd/even will do.
虽然你真的不需要pow
在这种情况下使用。一个简单的奇数/偶数测试就可以了。
double sum = 0;
int i = 1;
int n = 5;
for(i = 1; i <= n; i++){
double val = (double)i / (i + 1);
if (i % 2 != 0){
val *= -1.;
}
sum += val;
}
回答by ClemPi
You need too put sum += pow(-1,i)*(i/(i+1));
你也需要 put sum += pow(-1,i)*(i/(i+1));
Otherwise you lose previous result each time.
否则你每次都会失去之前的结果。
Use pow function for pow operation.
使用 pow 函数进行 pow 操作。
edit : as said in other post, use double or float instead of int to avoid truncated division.
编辑:如其他帖子所述,使用 double 或 float 代替 int 以避免截断除法。
回答by Sergey Brunov
How about this
这个怎么样
((i % 2) == 0 ? 1 : -1)
instead of
代替
std::pow(-1, i)
?
?
Full answer:
完整答案:
double sum = 0;
int i = 1.0;
int n = 5.0;
for (i = 1; i <= n; ++i) {
signed char sign = ((i % 2) == 0 ? 1 : -1);
sum += sign * (i / (i+1));
}
回答by Rob?
You seem to have a few things wrong with your code:
您的代码似乎有一些问题:
using namespace std;
This is not directly related to your problem at hand, but don't ever say using namespace std;
It introduces subtle bugs.
这与您手头的问题没有直接关系,但永远不要说它using namespace std;
引入了微妙的错误。
int i = 1.0;
int n = 5.0;
You are initializaing integral variables with floating-point constants. Try
您正在使用浮点常量初始化整数变量。尝试
int i = 1;
int n = 5;
sum = (-1)^i*(i/(i+1));
You have two problems with this expression. First, the quantity (i/(i+1))
is always zero. Remember dividing two int
s rounds the result. Second, ^
doesn't do what you think it does. It is the exclusive-or operator, not the exponentiation operator. Third, ^
binds less tightly than *
, so your expression is:
这个表达式有两个问题。首先,数量(i/(i+1))
始终为零。记住除以两个int
s 舍入结果。其次,^
没有做你认为它会做的事情。它是异或运算符,而不是幂运算符。第三,^
绑定不那么紧密*
,所以你的表达式是:
-1 xor (i * (i/(i+1)))
-1 xor (i * 0)
-1 xor 0
-1
回答by Sid
Few problems:
几个问题:
^ is teh bitwise exclusive or in c++ not "raised to power". Use pow() method.
Remove the dangling opening bracket from the last line
Use ints not floats when assigning to ints.
^ 是按位排他的,或者在 C++ 中不是“提升到权力”。使用 pow() 方法。
从最后一行中删除悬空的开口支架
分配给整数时使用整数而不是浮点数。
回答by ssell
^
does not do what you think it does. Also there are some other mistakes in your code.
^
不会做你认为它会做的事情。您的代码中还有一些其他错误。
What it should be:
它应该是什么:
#include <iostream>
#include <cmath>
int main( )
{
long sum = 0;
int i = 1;
int n = 5;
for( i = 1; i <= n; i++ )
sum += std::pow( -1.f, i ) * ( i / ( i + 1 ) );
std::cout << "Sum = " << sum << std::endl;
return 0;
}
To take a power of a value, use std::pow
(see here). Also you can not assign int
to a decimal value. For that you need to use float
or double
.
要获取值的幂,请使用std::pow
(请参见此处)。您也不能分配int
给十进制值。为此,您需要使用float
或double
。
The aforementioned ^
is a bitwise-XOR, not a mark for an exponent.
上述^
是按位异或,而不是指数的标记。
Also be careful of Integer Arithmeticas you may get unexpected results. You most likely want to change your variables to either float
or double
.
还要小心整数运算,因为您可能会得到意想不到的结果。您很可能希望将变量更改为float
或double
。
回答by Andrei
There are a few issues with the code:
代码有几个问题:
int sum = 0;
The intermediate results are not integers, this should be a double
中间结果不是整数,应该是double
int i = 1.0;
Since you will use this in a division, it should be a double, 1/2 is 0 if calculated in integers.
由于您将在除法中使用它,因此它应该是双精度数,如果以整数计算,则 1/2 为 0。
int n = 5.0;
This is an int, not a floating point value, no .0 is needed.
这是一个整数,不是浮点值,不需要 .0。
for(i=1;i<=n;i++)
You've already initialized i to 1, why do it again?
你已经将 i 初始化为 1,为什么还要初始化?
sum = (-1)^i*(i/(i+1));
Every iteration you lose the previous value, you should use sum+= 'new values'
每次迭代都会丢失以前的值,您应该使用 sum+= 'new values'
Also, you don't need pow to calculate (-1)^i
, all this does is switch between +1 and -1 depending on the odd/even status of i
. You can do this easier with an if
statement or with 2 for
's, one for odd i
one for even ones... Many choices really.
此外,您不需要 pow 来计算(-1)^i
,所有这些都是根据 的奇数/偶数状态在 +1 和 -1 之间切换i
。您可以使用if
语句或 2更容易地做到这一点for
,一个表示奇数,i
一个表示偶数……确实有很多选择。