gpt4 book ai didi

c - 寻找第二高的数字

转载 作者:太空宇宙 更新时间:2023-11-04 05:49:49 25 4
gpt4 key购买 nike

我想在不使用数组的情况下从序列中找到第二大的数字

说明如下。

You are given a sequence of integers as input, terminated by a -1. (That is, the input integers may be positive, negative or 0. A -1 in the input signals the end of the input.)

-1 is not considered as part of the input.

Find the second largest number in the input. You may not use arrays.

我做的是这个。

#include <stdio.h>

int main(void) {
int i, a, temp, sec;
while (1) {
scanf("%d", &a);
if (a == -1) ;
break;

temp = a;
while (1) {
scanf("%d", &a);
if (a == -1) {
break;
}
if (a > temp)
sec = temp;
else
sec = a;
}
}

printf("%d", sec);
return 0;
}

示例测试用例如下所示。

Sample Test Cases
Input
Test Case 1
-840 -288 -261 -337 -335 488 -1
Output
-261
Test Case 2
-840 -335 -1
Output
-840

我不知道从哪里开始,我哪里出错了。

最佳答案

我不会解决你的作业,但会提供一些提示:

  1. 您应该为您的变量起一个清晰的名称,以反射(reflect)它们的用途。 iatempsec 等名称使代码变得难以推理。

  2. 您应该初始化所有变量。例如,sec 的初始化有点不确定。

  3. 你不需要两个循环。

  4. 下面的if是一个空操作(这意味着后面的break是无条件执行的):

    if (a == -1) ;

最后,也是最重要的,在迭代数字时需要处理三种情况:

  1. 当前数字大于迄今为止看到的最大数字。

  2. 当前的数字不大于最大的数字,但大于迄今为止看到的第二大数字。

  3. 当前数不大于第二大数。

希望这能为您提供足够的指导,让您取得更大的进步。如果您遇到困难,请发布另一个问题。

关于c - 寻找第二高的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45468165/

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