My C++ output is always 0

This question already has an answer here:

  • Why is this program erroneously rejected by three C++ compilers? 31 answers

  • You need to enter the values of "a" and "b" before the initialization of "c".

    As it stands when calculating "c" both "a" and "b" are empty.

    Also you will have loss of precision because c is not a double.


    Unfortunately, you're doing the calculation (a / 5) * b on two empty undefined numbers. Consider this, if you're reading your code from top to bottom (which is often how languages interpret functions), each statement would be interpreted as:

    Create 'a' as an integer... (Since you didn't give it a value, I won't guarantee one for you.) in line "int a;"
    Create 'b' as an integer... (You also didn't give me a value, I'll just set it to whatever was last in the location in memory.) in line "int b;"
    Divide 'a' by 5 (Since you didn't explicitly provide 'a' a value, it would be hard to predict the result.) at "(a / 5)" in line "(a / 5) * b"
    Multiply the last calculation by b (You didn't provide 'b' a value either, so you're creating a wildly unpredictable equation). at " * b" in line "(a / 5) * b;"
    Fill in the value 'a' (Now you're actually filling in a, but you already did your calculation.) in line "cin >> a;"
    Fill in the value 'b' (Same for variable b) in line "cin >> b;"
    

    What you're experiencing is C++ undefined behavior. Basically, because you didn't set either 'a' or 'b' a value, it'll just leave whatever was last in it's spot in memory as it's value. You can read more about it here: https://en.wikipedia.org/wiki/Undefined_behavior

    To solve this, run the two "cin >> x" operations before the calculation, but not before the declarations (or "int a; int b;").

    Sorry about misusing the code selection. I felt like it wouldn't look right without it.

    链接地址: http://www.djcxy.com/p/86296.html

    上一篇: 为什么我的程序在法语下不能在Windows 7下编译?

    下一篇: 我的C ++输出始终为0