当我使用十进制值时,为什么我的计算器重复相同的输出

  • 本文关键字:计算器 输出 十进制 c++ math
  • 更新时间 :
  • 英文 :


我已经编写了这段代码。它运行得很好,不过我很好奇。当我在其中一个函数中添加十进制数时,为什么我的其他函数重复相同的代码并完成?我知道当我把输入的数字指定为双时它是有效的。我很好奇为什么它会这么有趣。

#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

为什么我的其余函数重复相同的代码并完成?

这是因为当CCD_ 1的提取失败时,导致提取失败的字符留在流中(每次尝试新的提取时都会遇到(,并且流被设置为失败状态,从而进一步尝试从失败的流中提取数据-因此,您之前为num1num2设置的任何值都将被反复使用。如果没有赋值,则读取未初始化的内存,并且程序具有未定义的行为。

要从失败的提取中恢复,您可以clear()流的状态标志,ignore()流中的字符,直到行尾。

此外,您的request()函数和其他函数无论如何都有未定义的行为。它们被声明为返回int,但不返回任何内容,所以改为void

但是,您可以更改request()以返回int0。如果请求成功则返回true,否则返回false

#include <limits> // std::numeric_limits
bool request() {
cout << "Type in a number: ";
if(cin >> num1) {
cout << "Type in a number: ";
if(cin >> num2) return true;     // both numbers extracted successfully
}
// something failed
if(not cin.eof()) { // skip clearing the state if eof() is the reason for the failure
cin.clear();    // clear the fail 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 getMin() {   // made it void since it doesn't return anything
cout << "Get the minimum of 2 numbers" << endl;
if(request()) {               // check that extraction succeeded
if(num1 < num2)
cout << "The minimumm of " << num1 << " and "
<< num2 << " is " << num1 << endl;
else
cout << "The minimumm of " << num1 << " and "
<< num2 << " is " << num2 << endl;
}
}

最新更新