gpt4 book ai didi

c++ - 如何使用条件语句返回指针?

转载 作者:太空狗 更新时间:2023-10-29 23:26:37 26 4
gpt4 key购买 nike

以下代码输出第二个数字作为最大值。如果您需要任何其他信息,请告诉我。

#include <iostream>                                                     
#include <cstdlib>
using namespace std;
double *ComputeMaximum(const double *Max, const double *Min);

double *ComputeMaximum(const double *Max, const double *Min)
{
return ((double *)((&Max > &Min) ? Max : Min));
}

int main(void)
{
double *max;
double Initial, Secondary;


cout << "Enter the number followed by space then another number: ";
cin >> Initial;
cout << "\nIn-" << Initial;
cin >> Secondary;
cout << "\nSe-" << Secondary;
//cout >> "Of " >> Inital >> "and " >> Secondary;
//cout >> "the maximum is " >>
max = ComputeMaximum((double*)&Initial,(double*)&Secondary);
cout << "\nmax" << *max;
return 0;
}

下一段代码输出第一个数字作为最大值

#include <iostream>                                                     
#include <cstdlib>
using namespace std;
double *ComputeMaximum(const double *Max, const double *Min);

double *ComputeMaximum(const double *Max, const double *Min)
{
return ((double *)((Max > Min) ? Max : Min)); // Here is the difference(& missing)
}

int main(void)
{
double *max;
double Initial, Secondary;


cout << "Enter the number followed by space then another number: ";
cin >> Initial;
cout << "\nIn-" << Initial;
cin >> Secondary;
cout << "\nSe-" << Secondary;
//cout >> "Of " >> Inital >> "and " >> Secondary;
//cout >> "the maximum is " >>
max = ComputeMaximum((double*)&Initial,(double*)&Secondary);
cout << "\nmax" << *max;
return 0;
}

哪里做错了?我只需要最大值,不需要第二个或第一个输入。我得到了答案。谢谢大家。

这里是:

#include <iostream>                                                     
#include <cstdlib>
using namespace std;
double *ComputeMaximum(const double *Max, const double *Min);

double *ComputeMaximum(const double *Max, const double *Min)
{
return (double*)((*Max > *Min) ? Max : Min);
}

int main(void)
{
double *max;
double Initial, Secondary;


cout << "Enter the number followed by space then another number: ";
cin >> Initial;
cout << "\nIn-" << Initial;
cin >> Secondary;
cout << "\nSe-" << Secondary;
//cout >> "Of " >> Inital >> "and " >> Secondary;
//cout >> "the maximum is " >>
max = ComputeMaximum(&Initial, &Secondary);
cout << "\nmax" << *max;
return 0;
}

最佳答案

double *ComputeMaximum(const double *Max, const double *Min)
{
return *Max > *Min ? Max : Min;
}

请注意,我使用了 *Max*Min 而不是 &Max&Min,即取消引用,而不是地址!另请注意,对于已经是所需类型的表达式,您有很多不必要的转换为 double* 。一个例子是您的 ComputeMaximum 函数体。另一个例子

max = ComputeMaximum((double*)&Initial,(double*)&Secondary);

因为InitialSecondarydouble类型,&Initial&Secondary属于 double* 类型,因此绝对不需要丑陋的不必要的转换。只需使用

max = ComputeMaximum(&Initial,&Secondary);

其他地方也类似。

我强烈推荐你阅读a good book on C++ .

关于c++ - 如何使用条件语句返回指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13119443/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com