What is wrong with this c++ code?

#include <iostream>

int main () {
std::cout << "What is your favourite number? " << std::endl;
int iNumber;
std::cin >> iNumber;
std::cout << "Your favourite number is " << iNumber << std::endl;
return 0;
}


It's just elementary code I have been learning from a youtube tutorial, as I am totally new to this. Since int doesn't handle fractions (correct me if I'm wrong), I decided I would like to make the program more complex so as to allow for fractions. I elaborated on the code as follows:

#include <iostream>

int main () {
std::cout << "What is your favourite number? " << std::endl;
int iNumber;
std::cin >> iNumber;
std::cout << "Your favourite number is " << iNumber << std::endl;
double dNumber;
std::cin >> dNumber;
std::cout << "Your favourite number is " << dNumber << std::endl;
return 0;
}

If I input my favourite number as 1.5 for example, the program tells me "Your favourite number is 1" and also "Your favourite number is 0.5". Obviously I am overlooking something. Could someone tell me what I'm doing wrong? Thanks.
I should also have pointed out that I would like the program to say "Your favourite number is 1.5". Thanks again.
#include <iostream>
using namespace std;                                    // to omit the std::
int main () {
cout <<"What is your favourite number? ";
float iNumber;                                                //you can use float here
cin >> iNumber;
cout <<"Your favourite number is " << iNumber;
return 0;
} 


still a begginer here too.
hope I've helped you
you might what to declare your variables first like so
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

#include <iostream>

using namespace std;

int main( )
{
    // declare variables here

    double favorNumber; // double is a float-point variable type which takes all real numbers         and whole numbers

    //end variables

    cout << "What is your favorite number? ";
    cin >> favorNumber; // the user enter his/her favorite number

    cout << "Your favorite number is " << favorNumber << endl; // the programmer print there favorite number to the screen 

    return( 0 );
}



Last edited on
Topic archived. No new replies allowed.