数学复发

时间:2016-03-17 11:41:08

标签: c++ recurrence

很抱歉这是我第一次使用stackoverflow。

我不知道我的代码中的错误在哪里。

我想要的输出:

-1+3-5+7-9+11-13+15
RESULT : 8

但显示的输出

-1+3-5+7-9+11-13+15
RESULT : 10
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
    int i, S, x, sign;
    S = 0;
    for (i = 1; i <= 8; i++) {
        if ((pow(-1, i - 1) == 1) && (i > 1)) {
            sign = -1;
        }
        if ((pow(-1, i - 1) != 1) && (i > 1)) {
            sign = 1;
            cout << "+";
        }
        if (i == 1) {
            sign = 1;
            cout << "-";
        }
        x = sign * (2 * i - 1);
        cout << x;
        S = S + x;
    }
    cout << "\n Result:" << S;
}

4 个答案:

答案 0 :(得分:3)

问题出现在if条件块中,您检查i==1 在该循环中,您sign=1应该是sign=-1

答案 1 :(得分:2)

如何改进逻辑如下?

#include <iostream>

using namespace std;

int main()
{
    int i;
    bool sign = true; // signed/minus = true, non-signed/plus = false
    int ans = 0;

    for( i=1; i<=15; i=i+2){
        if( sign == true){
            cout << "-" << i;
            ans = ans - i;
        }
        else {
            cout << "+" << i;
            ans = ans + i;
        }
        sign = !sign;
    }
    cout << endl << "RESULT : " << ans << endl;
    return 0;
}

答案 2 :(得分:1)

试试此代码

 #include <iostream>
 #include <math.h>
 using namespace std;
 int main() 
 {
   int i, S, x, sign;
   S = 0;
   for (i = 1; i <= 8; i++) {
     if ((pow(-1, i - 1) == 1) && (i > 1)) {
        sign = -1;
     }
     else
     if ((pow(-1, i - 1) != 1) && (i > 1)) {
        sign = 1;
       // cout << "+";
     }
     //else
     if (i == 1) {
        sign = -1;
        //cout << "-";
     }
     x = sign * (2 * i - 1);
     cout <<"\n"<<x;
     S = S + x;
    //cout<<"S is \n"<<S;
  }
  cout << "\n Result:" << S;
}

i==1

时出现了错误的符号

答案 3 :(得分:0)

问题在于您以积极的sign开始计算(但是您通过打印"-"对自己说谎。)

你可以简化代码,如果你进行了obervation,就不需要使用pow

pow(-1, k) == -1 * pow(-1, k-1)

pow(-1,0)开始(即1),您可以写:

int main(int argc, char* argv[])
{
    int sign = 1;  // sign will always hold pow(-1, i).
    int sum = 0;
    for (int i = 1; i <= 8; i++)
    {
        sign *= -1;
        if (sign > 0)  // Since sign starts at -1, we know that i > 1 here
        {
            std::cout << "+";
        }
        int term = sign * (2 * i - 1);
        std::cout << term;
        sum += term;
    }
    std::cout << " = " << sum << std::endl;
}