小明学会了用程序找出数组中最小的数和最大的数,现在他想编写一段程序找出一串数中第二小的数,相同的数名次并列,现在请你和他一起,找出数组中出现的第二小的数.
时间: 2023-04-06 13:03:30 浏览: 49
好的,我可以回答这个问题。可以使用以下代码来找出数组中第二小的数:
```
int[] arr = {3, 5, 2, 8, 1, 9, 4, 7, 6};
int min = Integer.MAX_VALUE;
int secondMin = Integer.MAX_VALUE;
for (int i = 0; i < arr.length; i++) {
if (arr[i] < min) {
secondMin = min;
min = arr[i];
} else if (arr[i] < secondMin && arr[i] != min) {
secondMin = arr[i];
}
}
System.out.println("第二小的数是:" + secondMin);
```
这段代码会遍历整个数组,同时记录下最小值和第二小的值,最后输出第二小的值。
相关问题
编写一个C语言程序输入小明的四科成绩求成绩总和和平均分,并找出最大值和最小值
好的,以下是一个C语言程序,可以输入小明的四科成绩,求成绩总和和平均分,并找出最大值和最小值:
```
#include <stdio.h>
int main() {
float score1, score2, score3, score4;
float sum, average;
float max, min;
printf("请输入小明的四科成绩:\n");
scanf("%f%f%f%f", &score1, &score2, &score3, &score4);
sum = score1 + score2 + score3 + score4;
average = sum / 4;
max = score1;
if (score2 > max) {
max = score2;
}
if (score3 > max) {
max = score3;
}
if (score4 > max) {
max = score4;
}
min = score1;
if (score2 < min) {
min = score2;
}
if (score3 < min) {
min = score3;
}
if (score4 < min) {
min = score4;
}
printf("成绩总和为:%.2f\n", sum);
printf("平均分为:%.2f\n", average);
printf("最高分为:%.2f\n", max);
printf("最低分为:%.2f\n", min);
return 0;
}
```
希望这个程序能够帮到你!
c语言小明想写一个实现数组元素的查找功能得小程序
可以使用以下代码实现:
```c
#include <stdio.h>
int main() {
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int target, index = -1;
printf("请输入要查找的数字:");
scanf("%d", &target);
for (int i = 0; i < 10; i++) {
if (arr[i] == target) {
index = i;
break;
}
}
if (index == -1) {
printf("数组中没有找到该数字\n");
} else {
printf("数字 %d 在数组中的下标为 %d\n", target, index);
}
return 0;
}
```
首先定义了一个包含 10 个元素的整型数组 `arr`,并初始化了数组的元素。
然后通过 `scanf` 函数从用户输入中读取要查找的数字 `target`。
接下来使用 `for` 循环遍历数组中的每个元素,如果找到了与 `target` 相等的元素,就记录该元素的下标 `index` 并使用 `break` 跳出循环。
最后根据 `index` 的值输出查找结果。如果 `index` 仍然是初始值 -1,说明数组中没有找到该数字;否则输出该数字在数组中的下标。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)