我一直在编写一些简单的算法,但遇到了一个问题。我正在编写一个算法来显示数字的最小值和最大值。它有效,但它只返回两种情况下的最大值,我不明白为什么。非常感谢!!!
#include <iostream>
using namespace std;
void Citire(int& n)
{ cout <<"\nDa numarul:";
cin >>n;
while (n<=0)
{cout<<"ai gresit, da natural:";
cin >>n;
}
}
int CifMinMax(int n)
{
int Max = 9;
int Min = 0;
int UltCif;
while (n>0)
{
UltCif = n % 10;
if (UltCif < Min)
Min = UltCif;
if (UltCif > Max)
Max = UltCif;
n = n/10;
}
return Max, Min;
}
int main()
{
int n;
int Min;
int Max;
Citire(n);
Min = CifMinMax(n);
Max = CifMinMax(n);
cout <<endl<<Min<<" este cifra minima a numarului, iar "<<Max<<" este cifra maxima a numarului." << endl;
return 0;
}
最佳答案
return Max, Min;
此行实际上返回 Min
并丢弃 Max
。阅读有关 operator 的信息,
它从左到右评估其操作数并返回最后一个,这就是您获得相同值的原因。
你需要这样的东西:
std::pair<int, int> CifMinMax(int n)
{
// ...
return std::make_pair(Min, Max);
}
std::pair<int, int> MinMax = CifMinMax(n);
Min = MinMax.first;
Max = MinMax.second;
关于c++ - 为什么我的 C++ 算法总是为数字的最小值和最大值返回相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26717220/