gpt4 book ai didi

计算最大数字出现的次数

转载 作者:行者123 更新时间:2023-11-30 17:20:42 25 4
gpt4 key购买 nike

我一直在尝试编写一个程序,将输入存储到数组中,然后允许我将其打印出来。它还让我知道哪个数字是最大的。我想弄清楚的是如何让我的程序告诉我输入数组中最大数字的次数(出现次数)。到目前为止,这是我的代码。截至目前,这段代码输出了我输入到数组中的数字、数组中最大的元素以及我输入的每个数字的出现次数(数字的出现次数是不正确的)。总而言之,每个数字出现的次数都是 0。这显然是不正确的。同样,我需要我的程序显示最大的数字(它确实如此)以及仅最大数字的出现次数。欢迎所有建议、提示或想法。谢谢。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>



int main()
{
int arrayNum[15];
int a;
int max=0;
int location;


for( a=0; a < 15; a++)
{
printf("Enter element %d:", a);
scanf("%d",&arrayNum[a]);
}

for(a=0; a < 15; a++)
{
printf("%d\n", arrayNum[a]);
}

for (a = 1; a < 15; a++)
{
if (arrayNum[a] > max)
{
max = arrayNum[a];
location = a+1;
}
}
printf("Max element in the array in the location %d and its value %d\n", location, max);

for(a=0; a<15; a++)
{
if(arrayNum[a+1] == arrayNum[a])
continue;
else
printf("Number %d: %d occurences\n", arrayNum[a]);
}
return 0;





}

最佳答案

我发现您的代码中存在一些问题。首先,第三个 for 循环从 1 开始,但它不会将 max 更新为 arrayNum[0] 的值。

然后,对于手头的问题,我有两个变量:

int max; // The maximum value
int max_count; // The count of the maximum value

然后,找到最大的值和计数的逻辑如下:

对于每个元素,将其与看到的最大值进行比较。如果相等,则增加 max_count。如果较大,则用该值更新 max,并将 max_count 设置为 1。如果较小,则忽略它。像这样的东西:

max = arrayNum[0];
max_count = 1;
for (int a = 1; a < 15; ++a)
{
if (arrayNum[a] == max)
max_count++;
else if (arrayNum[a] > max)
{
max_count = 1;
max = arrayNum[a];
}
}

关于计算最大数字出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28473420/

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