C++ Fibonacci Almost done, Just need 1 more thing to add.

Hey everyone,

I was told to write a Fibbonaci program:

You are to write a program that asks the use to enter an integer n and then print out the Fibonacci sequence that ends with the number Fn. Your sequence should be separated with commas and a period should follow the last number. Example:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34.

Your program should check that the integer n is greater than or equal to zero. If not, you should just print an error message.

I have everything down but the only thing is that I don't know how to get the period at the end. Also, when I enter 100 for the Fn, I start to get negatives, you can try out my code, is that normal? Thanks for the help =)

My Code:

#include "stdafx.h"
#include <iostream>
using namespace std;


int main()
{
    int num;
    
    cout << "How many Fibonacci numbers do you want to display?";
    cin >> num;
    
    if (num >= 0 && num <= 100)
    {
    int a = 0;
    int b = 1;
    int sum;
    
    for (int i = 0; i < num; i++)
    {
        cout << a << ", ";
        sum = a + b;
        a = b;
        b =sum;
    }

    }
    
    else

    cout << "Error! Please enter a number in the range of 0-100.";


system("pause");

return 0;

}







it gets negative because the number is greater than the value you can store in an int, try using a double, u shouldnt have a problem then!!
Thanks a lot ami. I used int main() and then replaced all ints with double in the code and now it doesnt show negatives. I still need that period at the end though if you happen to know haha =)
Topic archived. No new replies allowed.