首页 > 解决方案 > 使用 UserInput ,c ++ 查找最大和最小数字

问题描述

我试图创建一个在主函数中调用的函数,以允许用户输入任意数量的数字,直到输入“0”。使用此函数给出输入的值的数量以及这些值的总和以及输入的最高和最低数字。

好的,所以假设输入的所有数字都是整数...... SmallestNum 的输出总是不正确......我花了几天时间试图解决这个问题,感觉我忽略或遗漏了一些东西......

我错过了什么?

int MaxMin_Int(int& sum,int& count,int& LargestNum,int& SmallestNum)
{
    int num;
    
    do{
        cout<< "Enter Number (Press 0 to Exit): ";
        cin>>num;
        
        sum = sum + num;
        count++;                        //incerement count...

        
        if ( num > LargestNum)          // Store Largest number in variable LargestNum
            LargestNum = num;
        else if ( num > SmallestNum && num < LargestNum )
            SmallestNum = num;          //Store Smallest number in SmallestNum varaible
            
        

    }while(num != 0);
        count--;
                                
    

    
    return sum,count,LargestNum,SmallestNum;
}

int main(){
    
    //decleration of static variables
    int sum = 0;
    int count = 0;
    int LargestNum = 0;
    int SmallestNum = 1;
    
    //Loop that breaks Once User Enters '0'
    
    // Output the sum of numbers and number of numbers entered before program was executed.
    //Sum_int(count,sum);

    MaxMin_Int(sum,count,LargestNum,SmallestNum);
    
    cout<<"\n\n"<<count<<" Values Were Entered"<<endl;
    cout<<"With a sum of: "<<sum<<endl<<endl;
    
    // Out put Highest And Lowest Numbers
    
    
    cout<<"Largest Number Entered: "<< LargestNum <<endl;
    cout<<"Smallest Number Entered: "<< SmallestNum <<endl;
    
    

    return 0;
}

标签: c++function

解决方案


有一些问题。在第一个输入 ( count == 0) 之后,您必须设置LargestNumSmallestNum 。如果退出条件为 0,则忽略 0。使用条件 检测最小的数字if (num < SmallestNum)。参数通过引用传递。不需要返回值。

void MaxMin_Int(int& sum, int& count, int& LargestNum, int& SmallestNum)
{
    int num;
    
    sum = count = LargestNum = SmallestNum = 0;
    do {
        cout << "Enter Number (Press 0 to Exit): ";
        cin >> num;
        
        if (num != 0)
        {
            if (count == 0)
                LargestNum = SmallestNum = num;
            else if (num > LargestNum) 
                LargestNum = num;
            else if (num < SmallestNum)
                SmallestNum = num;   

            sum += num;
            count++;   
        }
    } while (num != 0);
}

推荐阅读