尝试开发一个程序来识别最小和最大的数字

时间:2015-02-19 08:13:08

标签: c++ algorithm

大家晚上好,我正在尝试编写能确定数字何时最大和最小的代码。我已经问了一些我认识的导师,他们也对此感到难过。我不能使用函数或数组或中断。 :/我的理解使这个过程变得更加困难。我的教授已经说过了

"循环中允许的唯一决策是确定最大值和最小值。这意味着您不能使用决定来确定是否输入了第一个号码。这将需要你填充你的循环。我们将在下一节中介绍启动循环,但对于此赋值,它意味着在循环开始之前获取第一个数字。我们还假设至少输入一个数字。"

我不明白他希望我们做一些我们还没有学到的东西,但不管怎样......这就是我在作业中取得的进展......

我们必须让用户输入一个值来确定输入多少个值...

在输入了我要检查的值之后,我一直收到错误消息,

"变量" num"正在使用而未被初始化。"但是num在int !!!

然后让软件基本上识别出最大和最小...希望这对某人有意义..如果您有任何疑问,或者如果我需要澄清任何事情请告诉我,我会尽力而为我的能力..

#include <iostream>
using namespace std;
int main ()
{
    int number;
    int max=0;
    int num;
    int min=0;


    {   cout << "How many numbers do you want to enter" ;
        cin >> number;

        for (int i=0; num!=number; i++)
        {

            cout<<"Enter a num "; /* This is where they are supposed to place in a number, press enter, another number, press enter, until their enter presses = number*/
            cin>>num;
            if (num>max)
                max=num;
            if (num<min)
                min=num;
        }
        cout<<"largest number is: "<<max << endl;
        cout<<"smallest number is: "<<min << endl;

    }
}

3 个答案:

答案 0 :(得分:4)

此:

for (int i=0; num!=number; i++)

有未定义的行为,num在首次评估时没有值。您的意思是i != number(或者更好,i < number)。

最好使用其他一些停止方式,例如在输入非数字时停止。

更新:只是为了澄清:还有其他问题,例如min没有以尽可能少的数字进行初始化。我可能会去min = INT_MAX;或类似的东西。有关该常量,请参阅<climits>

答案 1 :(得分:0)

int min=0;

您应该将其更改为

int min=std::numeric_limits<int>::max();   

否则,如果您输入的数字大于0,则不会将其分配给min

  

变量&#34; num&#34;正在使用而未被初始化..

num一个值,在循环开始之前没有给它一个值。但是这个循环概念本身是错误的,试试这个。

for (int i=0; i < number; i++)

答案 2 :(得分:0)

你的代码中有两个问题,首先你的min必须是一个很大的数字,比如最大整数,第二个是你的for循环应该循环i。我评论了你需要改变的行:)

#include <iostream>
#include <limits>
using namespace std;
int main ()
{
    int number;
    int max=0;
    int num;
    int min=std::numeric_limits<int>::max(); // change min to maximum integer possible in c++


    {
        cout << "How many numbers do you want to enter" ;
        cin >> number;

        //for (int i=0; num !=number; i++) change this line
        for (int i=0; i<number; i++)   //to this line
        {

            cout<<"Enter a num "; /* This is where they are supposed to place in a number, press enter, another number, press enter, until their enter presses = number*/
            cin>>num;
            if (num>max)
                max=num;
            if (num<min)
                min=num;
        }
        cout<<"largest number is: "<<max << endl;
        cout<<"smallest number is: "<<min << endl;

    }
}