比较C++的最小用户输入

Rau*_*ryn 0 c++ if-statement

我试图在3个输入中找到最小的数字.这是我的代码:

int main ()
{
     double x = 4.0;
     double y = 5.0;
     double z = 3.0;
     smallest(x,y,z);
     cout << smallest << endl;
     system("PAUSE");

}

double smallest(double x, double y, double z)
{
     double smallest;

     if ((x < y)||(x< z)) {
        smallest = x;
     } else if ((y < z)||(y < x)) {
        smallest = y;
     } else {
        smallest = z;
     }
     return smallest;

}
Run Code Online (Sandbox Code Playgroud)

但是,我一直在收到错误.它声明了我在main方法中使用未声明标识符的最小方法.这在使用eclipse但不是visual studio时有效.有人可以向我解释原因吗?

提前致谢.

更新部分.

所以我试着对这个程序进行验证.我想确保用户只输入号码,这里是我的代码:

    double x, y, z;
bool correct_input = false;
do{
    cout << "Enter first integer : " ;
    cin >> x;
    if(isdigit(x)){
        correct_input = true;
    }
}while(!correct_input);
do{
    cout << "Enter second integer : ";
    cin >> y;
    if(isdigit(y)){
        correct_input = true;
    }
}while(!correct_input);
do{
    cout << "Enter third integer : ";
    cin >> z;
    if(isdigit(z)){
        correct_input = true;
    }
}while(!correct_input);

cout << "Smallest integer is : " << smallest(x,y,z) << endl;
system("PAUSE");
Run Code Online (Sandbox Code Playgroud)

当我输入字母或除数字之外的任何内容时,我得到调试断言失败.在用户输入正确的输入之前,它不会提示.有人可以帮忙吗?

NPE*_*NPE 6

首先,如果您希望smallest()在定义之前使用,则需要对其进行原型设计.之前添加以下内容main():

double smallest(double x, double y, double z);
Run Code Online (Sandbox Code Playgroud)

此外,您忽略了返回值smallest().更改

smallest(x,y,z);
cout << smallest << endl;
Run Code Online (Sandbox Code Playgroud)

double smallest_val = smallest(x,y,z);
cout << smallest_val << endl;
Run Code Online (Sandbox Code Playgroud)


joh*_*ohn 5

这不是你问的问题,但你的功能被窃听,因为你困惑||&&.

你的功能应该是

double smallest(double x, double y, double z)
{
    double smallest;

    if (x < y && x < z)
        smallest = x;
    else if (y < z && y < x)
        smallest = y;
    else
        smallest = z;
    return smallest;
}
Run Code Online (Sandbox Code Playgroud)

x如果它是较小的y 并且它小于,则是最小的数字z.

更新

首先要说的是,如果你想整数,那么你应该使用int没有double.

第二件事,isdigit不做你认为它做的事情.你实际上已经为自己设定了一个非常棘手的问题.这是一种方法

#include <string> // for string class

bool correct_input = false;
do
{
    cout << "Enter first integer : " ;
    if (cin >> x)
    {
        correct_input = true;
    }
    else
    {
        // cin is in a error state after a failed read so clear it
        cin.clear();
        // ignore any remaining input to the end of the line
        string garbage;
        getline(cin, garbage);
    }
}
while(!correct_input);
Run Code Online (Sandbox Code Playgroud)

但这并不完美.例如,如果您输入abc,那么您的程序将要求输入更多,但如果您输入123abc,那么即使123abc不是有效数字,您也会得到整数123.

如果你真的想要这样做(并且很难),那么你必须读入一个字符串,检查字符串是否可以转换为数字,如果它可以进行转换,如果它不能再请求更多输入.