I have an assignment that requires me to create a code which displays the sum of all even fibonacci numbers. For example, the user inputs 15, the program should display - sum = 10. Determining the sum of all even fibonacci numbers less than or equal to 15 (2 and 8). I am wondering how to make the program display the sum of the even numbers.
You have three issues here. You're treating the value entered by the user as if it is the number of terms to generate instead of the maximum value, you need to be able to detect if a value is even, and you need to actually sum the values (which you are not currently doing.)
Are you allowed to put your code in functions? Do you know how to detect if a value is even?
Thank you so much, being a beginner i'm very blind in code right now. I hadn't even thought to use functions. Sadly I don't know how to detect even values.
#include<iostream>
#include<string>
usingnamespace std;
// Not a fan of global variables, and there are other (better) ways to do this,
// but this requires the least amount of explanation. These two variables define
// state for our next_term function.
unsigned current_term = 0;
unsigned previous_term = 1;
unsigned next_term()
{
unsigned result = current_term;
unsigned next = current_term + previous_term;
previous_term = current_term;
current_term = next;
return result;
}
int main() {
//declarations
int userNum = 0;
bool isUserNumValid = false;
//get user input
while (isUserNumValid == false) {
cout << "Enter a whole number representing the maximum possible Fibonacci term allowed: " << endl;
cin >> userNum;
if (userNum > 0)
isUserNumValid = true;
else
isUserNumValid = false;
}
{
unsigned term = next_term();
unsigned evens_sum = 0;
while (term <= userNum)
{
// if term is even, add it to evens_sum
term = next_term();
}
cout << "Sum = " << evens_sum << endl;
}
}
To detect if a value is even, look up the modulus operator.
I'm learning too, this is just a question.
Had he been using doubles, floats or whatever, I wouldn't have blinked at the modulud operation suggestion, However, he's using using integers, so do you need still Modulus operators? Since dividing an integer always rounds down, Couldn't you as easily use something like this?
1 2 3 4 5
if (((usernum/2)*2)== usernum){
cout << "We have an even number! " << endl;
else
{
cout << "That's an odd number!" << endl;
First figure out how to compute the Fibonacci sequence up to the number you need it to. Once you have that figured out, use the for-loop and modulus (%) operator to access and sum up the even numbers in the sequence.
As cire said, you may want to split this program up into different functions.