gpt4 book ai didi

c++ - 在 C++ 中如何从一组数字中获取最大的整数?

转载 作者:行者123 更新时间:2023-11-27 22:35:16 26 4
gpt4 key购买 nike

如果你有一组数字,比如 a=4,b=5,c=8。有没有办法让程序打印出最大值。因此,例如,我的所有值都输出了 4、5、8。如何让程序输出最大的值? (我正在使用 C++)。我使用了 if 语句,但我觉得有更短的方法。在谷歌上,我一直在寻找 INT_MAX 但这不是显示 int 类型中的最大数字吗?

部分代码

int a = (rand()%6)+1;
int b = (rand()%6)+1;
int c = (rand()%6)+1;
cout << int a << int b << int c << endl; //I'm trying to get it to display the largest int out of this group

我删除了我的 if 语句,试图找到一种更好的方式来显示最大的组。

最佳答案

How can I get the program to output the largest value?

这个过程有两个步骤。

  1. 计算三个数中的最大值。
  2. 显示最大数量。

如果您被允许使用标准库中的函数,您可以使用 std::max计算你的数字的最大值。如果你不是,你将不得不自己写一个。假设您可以使用 std::max,您的代码需要:

int m = std::max({a, b, c});
cout << "maximum: " << m << endl;

它也可以是单行的。

cout << "maximum: " << std::max({a, b, c}) << endl;

关于c++ - 在 C++ 中如何从一组数字中获取最大的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55306657/

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