c - 意外的结果 - 寻找最大值和第二最大值

标签 c data-structures runtime-error tournament

我正在尝试用 C 语言实现一个简单的锦标赛。

#include <stdio.h>

int main(void) {
    int tourn[100], n, i;
    printf("Give n:");
    scanf("%d", &n);
    printf("\n n = %d \n", n);
    for(i = n; i <= (2*n)-1; i++)
        scanf("%d", &tourn[i]);
    build(tourn, n);
    printf("\n Max = %d \n",tourn[1]);
    printf("\n Next Max = %d \n",nextmax(tourn, n));
 }

 void build(int tourn[], int n) {
    int i;
    for(i = 2*n-2; i > 1; i = i-2)
        tourn[i/2] = max(tourn[i], tourn[i+1]);
  }  

 int nextmax(int tourn[],int n) {
    int i = 2;
    int next;
    next = min(tourn[2], tourn[3]);
    while(i <= 2*n-1) {
        if(tourn[i] > tourn[i+1]) {
            next = max(tourn[i+1], next);
            i = 2*i;
        }
        else {
            next = max(tourn[i], next);
            i = 2*(i+1);
        } 
    }
    return(next);
}

int max(int i,int j) {
    if(i > j)
        return i;
    else
        return j;
}                       

int min(int i,int j) {
    if(i < j)
        return i;
    else
        return j;
} 

n = 5 的输出和 1 2 3 4 5

是 最大值 = 4195048

下一个最大值 = 32588

并且此输出每次都会有少量变化!

如果我在构建函数之前放置一个测试 printf 命令,它不会执行。

有人可以找到错误/解释输出吗? 谢谢:)

最佳答案

你的代码对我来说似乎很糟糕。您不介意超出数组边界进行寻址,这是产生随机结果的好方法:

while(i <= 2*n-1){
        if(tourn[i]>tourn[i+1]){
                next = max(tourn[i+1],next);
                i=2*i;
        } else {  
                next = max(tourn[i],next);
                i=2*(i+1);
        } 
}

您的(逻辑)数组的大小为2n。如果i达到“最高”值,则测试tourn[i + 1],即tourn[2n]

关于c - 意外的结果 - 寻找最大值和第二最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21774303/

相关文章:

Java数据结构让一个方法只有在被调用N次后才会触发

Javascript 'object has no method' 错误

安卓.content.res.Resources$NotFoundException : String resource ID #0x12 - onLocationChanged()

c - 如何针对 GPU 优化 OpenCL 内核?

c++ - 计算插入排序和归并排序的效率(daa)

algorithm - 在三元搜索树中查找最长公共(public)前缀

runtime-error - 升级pip后DistributionNotFound错误

c - 如何从文件读取数据并清理并存储到文件

c - 如何编写自定义 printf?

generics - 在 Scala 中模拟可变参数模板