簡體   English   中英

它也不是最大/最小代碼我如何找出這個代碼?

[英]It is nor max/min code how do i figure out this code?

得到一個程序,它得到(三個整數)並顯示既不是最大值也不是最小值的值?

我試圖想出一種方法來獲得最大值和最小值之間的數字。 我的輸入是x,y,z,它們是(三個整數)如何獲得這個既不是最大值也不是最小值的數字?

int x,y,z,max,min,between;
cout<<"enter 3 integer values \n";
cin>>x>>y>>z,between;

if (x>y&&x>z)
    x=max;
else if (x<y&&x<z)
    x=min;
else if(y>z&&y>x)
    y=max;
else if (y<z&&y<x)
    y=min;
else if(!max==between&& !min==between)
    cout<<"not max or min is "<<between<<endl;

return 0;
}

我會知道這不是正確的代碼,但我知道路徑很近。

得到一個介於最大值和最小值之間的數字。 輸入(三個整數)

這基本上是三個數字的中位數。

一個簡單的解決方案是獲取數組中的元素,對它們進行排序,然后選擇中間元素,如下所示,

int elements[3] = ... // contains x,y,z
std::sort(std::begin(elements), std::end(elements)); // sorts the elements
elements[1] // pick the middle element

我假設所有數字都是不同的,否則沒有數字既不是最小值也不是最大值。 例如,在三個數字中,3、3 和 3,3 既是最小值又是最大值。 在這種情況下沒有解決方案。

使用此代碼,您可以比較前 2 個變量以查看其中的最大值,然后與另一個變量進行比較

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM