the code you posted works fine for me under a variety of compilers, however I would suggest a couple of improvements:
cout << input2 - 2*input1 <<endl;
I would change this to cout << input2 - (2*input1) <<endl;
I would also ensure that cin is totally clear before taking an input by using: the following modified code:
cout << "Enter first input." << endl;
cin.clear();
cin >> input1;
cout << "Enter second input." <<endl;
cin.clear();
cin >> input2;
I only once managed to replicate your error by happenstance and it was occurring because the inputs were not set correctly.
After that I stepped through the program a few times and checked outputs: when the variables are not set correctly (i.e. they contain whatever value happens to be at the memory location utilised by the variable) I consistently get answers similar to your posted one.
So the simple answer is that the variables are un-initialised because the cin buffer is not cleared.
Hope this helps, and let me know if you need a better/more in-depth explanation:)
Addendum:
A few more points I just thought of on reading the other comments:
using namespace std;
- this is fine for small projects you control totally, ie homework, small assignments etc. however, when you are using diverse code (other libraries, APIs etc) it is more advisable to control namespaces directly: they exist to allow you to target specific functionality within a given namespace, and avoid name contention/ambiguity in the the code. For example you might call cin at present, later though you might include another API in you code, lets call it TEST namespace, so you add using namespace TEST
; TEST contains its own implementation of cin, which handles cin clearing automatically (handy because that may solve you problem) however your code cant compile now because you have std::cin
and TEST::cin
both available, and because you use the using namespace for both, when you type cin it could be either.
There was also a suggestion that you use float and not double, couple of points on this:
- using float or double will allow decimal values= TRUE
- using float rather than double will fix you problem= very very rarely True, there are limited instances where the bit-size of a float will fix a problem that the bit-size of a double caused.
- general programming convention: for memory efficiency, utilise the smallest possible type which can contain all your use-case values (a double is nominally twice the size of a float in memory, so
0.3f
is half the memory usage of 0.3d
I know this is for homework, as you mentioned that's why I have added the extra information,: it is always good to get more information, whether you agree with it or not having it will allow you to research more in-depth and either agree/prove or disagree/disprove the initial information you had. Welcome to programming, btw, it only gets worse!
Better! I meant better!