Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

c++ - I have a problem with this function, the output results are incorrect

I am trying to make something like this:

2^1 + 2^2 + 2^3 + 2^4 + ... + 2^n

This is my code:

#include <iostream>

int main(){
    int n, p=0;
    std::cout<<"N: ";
    std::cin>>n;
    
    for(int i=1; i<=n; i++){
        p = p+(2^i);
    }
    std::cout<<p;

    return 0;
}

The result is always incorrect. If I input 4, the result is 10. If I input 5, the result is 17 I think the problem is in p = p+(2^i); but I am not sure.

question from:https://stackoverflow.com/questions/66055636/i-have-a-problem-with-this-function-the-output-results-are-incorrect

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Notice that each term is a power of 2, which can be represented using the left shift operator:

for (int i = 0; i < N; ++i)
{
  p = p + (1 << i);
}

You could also note that each term is 2 times the previous term.
Thus you could write it also as:

unsigned int term = 1;
unsigned int sum_of_terms = 0;
for (int i = 0; i < N; ++i)
{
    sum_of_terms += term;
    term *= 2;
}

Edit 1: The Exclusive Or truth table
The operator^ is the **Exclusive-Or` operator. It works with bits.
Here's the truth table based on two bits:

  X  |  Y  | X ^ Y  
------------------  
  0  |  0  |  0  
  0  |  1  |  1  
  1  |  0  |  1  
  1  |  1  |  0  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...