我已经编写了这段代码。效果很好,不过我很好奇。当我在其中一个函数中添加十进制数时,为什么我的其余函数会重复相同的代码并完成?我知道将数字输入分配为双精度时可以使用。我很好奇,但为什么它会像这样发挥作用。
#include <iostream>
#include <cmath>
using namespace std;
int num1, num2;
int request(){
cout << "Type in a number: " << flush;
cin >> num1;
cout << "Type in a number: " << flush;
cin >> num2;
}
int getMin(){
cout << "Get the minimum of 2 numbers" << endl;
request();
if(num1 < num2)
cout << "The minimumm of " << num1 << " and "
<< num2 << " is " << num1 << endl;
else
cout << "The minimumm of " << num1 << " and "
<< num2 << " is " << num2 << endl;
}
int getMax(){
cout << "Get the maximum of 2 numbers" << endl;
request();
if(num1 > num2)
cout << "The maximum of " << num1 << " and "
<< num2 << " is " << num1 << endl;
else
cout << "The maximum of " << num1 << " and "
<< num2 << " is " << num2 << endl;
}
int power(){
cout << "Get the exponent of 2 numbers" << endl;
request();
cout << num1 << " to the power of " << num2 << " is "
<< pow(num1,num2) << endl;
}
int main(){
getMin();
cout << endl;
getMax();
cout << endl;
power();
cout << endl;
}
output
Get the minimum of 2 numbers
Type in a number: 5.5
Type in a number: The minimumm of 5 and 0 is 0
Get the maximum of 2 numbers
Type in a number: Type in a number: The maximum of 5 and 0 is 5
Get the exponent of 2 numbers
Type in a number: Type in a number: 5 to the power of 0 is 1
为什么我的其余函数会重复相同的代码并完成?
这是因为当int
提取失败时,导致提取失败的字符会留在流中(每次尝试新的提取时都会遇到),因此,您先前为num1
设置的任何值]和num2
将被重复使用。如果未分配任何值,则读取未初始化的内存,并且程序具有未定义的行为。
此外,您的request()
函数和其余函数仍然具有未定义的行为。声明它们返回int
,但不返回任何内容。
但是,如果请求成功,则可以将request()
更改为返回true
,否则为false
:
bool request() {
cout << "Type in a number: ";
if(cin >> num1) {
cout << "Type in a number: ";
if(cin >> num2) return true;
}
if(not cin.eof()) { // skip clearing the state if eof() is the reason for the failure
cin.clear(); // clear any error state
// ignore rest of line to remove the erroneous input from the stream
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
return false;
}
您现在可以使用它,并确保用户实际输入了两个值。
使其他函数不返回任何内容void