gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:53:52 24 4
gpt4 key购买 nike

我参加了一个 C++ 类(class),并且我有一些 Java 经验,但是我编写的这个程序无法正常工作。

我想做的是显示输入的两个值的最大、最小、总和、差、乘积和比率,但每次输入时它给我的结果都是 0。

#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;
}

最佳答案

这里有错误:

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。

关于C++ 用户错误,忽略变量条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22445588/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com