这是一个问题:编写具有五个参数的函数minMax的定义.前三个参数是整数.最后两个由函数设置为前三个参数的最大值和最小值.该函数不返回值.
该功能可以使用如下:
int a = 31, b = 5, c = 19, big, small;
minMax(a, b, c, &big, &small); /* big is now 31; small is now 5 */
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
void minMax(int x, int y, int z, int* big, int* small)
{
if (x < y && x < z)
*small = x;
else if (y < x && y < z)
*small = y;
else if (z < x && z < y)
*small = z;
if (x > y && x > z)
*big = x;
else if (y > x && y > z)
*big = y;
else if (z > x && z > y)
*big = z;
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误:
你的功能没有改变它的值small.确保在功能中取消引用它.
不确定是什么问题?
谢谢.
我看到一个直接的问题.
你觉得当你通过数字会发生1,1和7?
也许你可能要考虑使用的<=和>=,而不是仅仅<和>.
由于该错误消息看起来不像我之前看到的任何编译器错误(并且代码在语法上有效),我建议消息来自测试工具,可能:
big/small值设置为除传入的数字之外的数字(例如,-9999).1,1,7).此外,它不是世界上最易读的代码(没有违法行为).如果您能够以一种明确的意图(包括适当的评论)的方式构建您的代码,您将有大批未来的程序员歌颂您的赞美并崇拜您的名字:-)
像这样的东西显示的意图(IMNSHO)比许多这些else if结构更清楚:
// Populate big/small based on max/min of x, y and z.
void minMax (int x, int y, int z, int *big, int *small) {
// Set by default to x, only change if others are bigger.
*big = x;
if (y > *big) *big = y;
if (z > *big) *big = z;
// Same for small but with reversed comparisons.
*small = x;
if (y < *small) *small = y;
if (z < *small) *small = z;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1651 次 |
| 最近记录: |