我尝试了此代码的几种不同变体,但似乎无法正确执行。我对 C++ 还很陌生,所以这可以解释它。此代码是一个简单计算器的一部分。它基本上要求用户输入两个数字(它们可以是 float ),然后要求用户提供数学运算符,然后进行运算。如果用户输入的不是数字,然后在 if 语句中要求再次输入数字时输入数字,控制台将打印“-9.25596e+061”。这是代码:
#include "stdafx.h"
#include <iostream>
#include <cctype>
using namespace std;
double getUserInput()
{
//Make double, assign double, return double if number
double dUserInput;
//checks if it failed to cin
if (!(cin >> dUserInput))
{
//statement is true
cin.clear();
cin.ignore(99999, '\n');
cout << "You did not enter a number, please try again: ";
getUserInput();
}else
//statement if false
cout << "Number entered"; //for debugging purposes
return dUserInput;
}
最佳答案
您错过了在对 getUserInput
的递归调用中添加 return
。
换行
getUserInput();
到
return getUserInput();
更新
您可以将该函数更改为非递归版本。
double getUserInput()
{
//Make double, assign double, return double if number
double dUserInput;
//checks if it failed to cin
while (!(cin >> dUserInput))
{
cin.clear();
cin.ignore(99999, '\n');
cout << "You did not enter a number, please try again: ";
}
cout << "Number entered"; //for debugging purposes
return dUserInput;
}
关于c++ - 检查输入值是否为 float ,清除 cin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23789696/