C ++用户错误,忽略变量条目

时间:2014-03-17 01:42:28

标签: c++

我进入了一个C ++课程,我对Java有一些经验,但我做的这个程序并不起作用。

我想要做的是显示输入的两个值的最大,较小,总和,差异,乘积和比率,但是每次输入的所有值都是0。 / p>

#include "std_lib_facilities.h"

int main()
{
int val1 = 0;
int val2 = 0;
int greater_val = 0;
int smaller_val = 0;

cout << "Please enter one values, followed by enter, then another value.\n";
cin >> val1;
cin >> val2;

if (val1 > val2){
        val1 = greater_val;
        val2 = smaller_val;
    }
else if (val2 > val1){
        val2 = greater_val;
        val1 = smaller_val;
    }

cout << "Here are some statistics for the following values (" << val1 << " and " << val2 << "):";
cout << "\n\t Greatest value: " << greater_val;
cout << "\n\t Smallest value: " << smaller_val;
cout << "\n\t Sum: " << val1 + val2;
cout << "\n\t Difference: " << val1 - val2;
cout << "\n\t Product: " << val1 * val2;
cout << "\n\t Ratio: " << val1 / val2 << "\n\n";

return 0;
}

1 个答案:

答案 0 :(得分:2)

您在此处有错误:

if (val1 > val2){
    val1 = greater_val; //^^^should be greater_val = val1; same error apply below
    val2 = smaller_val;
}
else if (val2 > val1){
  //^^you probably don't need this if again, what if they are equal?
    val2 = greater_val;
    val1 = smaller_val;
}

由于greater_valsmaller_val被初始化为0,所以使用现在的代码,它们始终为零。

另一点:当你进行除法时,你必须确保val2不是0。