C++ 使用IF语句比较两个整数
嗨,我想用if语句解决一个实践问题,找到两个整数之间的最小值。说明是 声明一个要存储最小值的变量,如“min” 声明两个变量,要求用户输入两个整数并将它们保存到这些变量中 假设第一个整数是最小值,并将其保存到步骤1中声明的“min”变量中 编写一条if语句,比较这两个值并更新步骤1中的变量。如果操作正确,将不会有任何“else” 这是我的密码C++ 使用IF语句比较两个整数,c++,if-statement,min,C++,If Statement,Min,嗨,我想用if语句解决一个实践问题,找到两个整数之间的最小值。说明是 声明一个要存储最小值的变量,如“min” 声明两个变量,要求用户输入两个整数并将它们保存到这些变量中 假设第一个整数是最小值,并将其保存到步骤1中声明的“min”变量中 编写一条if语句,比较这两个值并更新步骤1中的变量。如果操作正确,将不会有任何“else” 这是我的密码 #include <iostream> using namespace std; int main () { int mins,a,b; c
#include <iostream>
using namespace std;
int main ()
{
int mins,a,b;
cout << "Enter two integers: ";
cin >> a >> b;
mins = a;
if (a<b)
{
cout << "The minimum of the two is " << mins;
}
else
return 0;
如果第一个整数高于第二个整数,程序就会跳到末尾,我的问题是它不会更新“分钟”。提前感谢您的程序逻辑错误。您希望这样做:
int main()
{
int mins, a, b;
cout << "Enter two integers: ";
cin >> a >> b;
if (a < b)
mins = a;
else
mins = b;
cout << "The minimum of the two is " << mins << endl;
return 0;
}
现在这仍然不是完全正确的,因为如果a和b相等,输出是不正确的
更正留给读者作为练习
编写一条if语句,比较这两个值并更新
步骤1中的变量如果您这样做,将不会有任何“其他”
正确地
我想你需要的是以下几点
#include <iostream>
using namespace std;
int main()
{
int min; // Step 1
int a, b; // Step 2
cout << "Enter two integers: ";
cin >> a >> b;
min = a; // Step 3
if ( b < a ) min = b; // Step 4
cout << "The minimum of the two is " << min << endl;
return 0;
}
因此,在答案中给出的代码中,只有我的代码做得正确。这是错误的
mins = a;
if (a<b)
{
cout << "The minimum of the two is " << mins;
}
else
应该是
if (a < b){
mins = a;
}
else{
mins = b;
}
cout << "The minimum of the two is " << mins;
如果满足以下条件,您可以使用shortland:
#include <iostream>
#include <algorithm>
int main() {
int a, b;
std::cout << "Enter a and b: ";
std::cin >> a >> b;
int min = (a>b) ? b : a;
std::cout << "The min element is: " << min;
}
如果你写了分钟=a;但这并不总是正确的。你已经有这种情况的案例了。只需在正确的大小写中为mins分配正确的值。您缺少else子句的内容。我建议在最后一个cout中添加换行符或endl,以刷新缓冲区:-@托马斯马修斯为什么?std::cout的析构函数已经这样做了。@nwp可能是因为SamD会很高兴看到在程序意外终止之前将消息刷新到输出流中。@nwp-因为从形式上讲,写入输出设备的文本行必须以换行符结尾。如果没有,它就不能保证被显示。@nwp-我没说它不会被刷新。但对于潜在的问题,请参见C11标准7.21.2/2:从文本流读入的数据必须与先前写入该流的数据进行比较,前提是:。。。最后一个字符是新行字符。
#include <iostream>
#include <algorithm>
int main() {
int a, b;
std::cout << "Enter a and b: ";
std::cin >> a >> b;
int min = (a>b) ? b : a;
std::cout << "The min element is: " << min;
}