Home>
#include<stdio.h>
#include<stdlib.h>
int main (void)
{
    char filename [21];
    FILE * fp;
    struct seisekiA {
        int bango, tokuten;
    };
    struct seisekiA seiseki [100];
    int n = 0, m = 1;
    int x, i, low, high;
    printf ("Please enter the file name \ n");
    scanf ("% s", filename);
    if ((fp = fopen (filename, "r")) == NULL)
    {
        printf ("FILE OPEN ERROR \ n");
        exit (1);
    }
    printf ("number score \ n");
    while (fscanf (fp, "% d% d",&seiseki [n] .bango,&seiseki [n] .tokuten)! = EOF)
    {
        printf ("% 4d% 4d \ n", seiseki [n] .bango, seiseki [n] .tokuten);
        n ++;
    }
    printf ("Number of records =% d \ n", n);
    fclose (fp);
    printf ("Enter number \ n");
    scanf ("% d",&x);
    low = 0;
    high = 100;
    i = (low + high)/2;
    while (low<= high&&x! = seiseki [i] .bango)
    {
        if (x<seiseki [i] .bango)
            high = i-1;
        else else
            low = i + 1;
        i = (low + high)/2;
        m ++;
    }
    printf ("access count =% d \ n", m);
    if (x == seiseki [i] .bango)
        printf ("% d point \ n", seiseki [i] .tokuten);
    else else
        printf ("not found");
    return 0;
}


This is a school issue.high = 100;Whenif (x == seiseki [i] .bango)/* ← Corrected * /Came when I was wrong. I don't know what to substitute for high.

I look forward to working with you.

c
  • Answer # 1

    It is assumed that the grade numbers have been sorted in ascending order.
    high = 99By doing so, you can eliminate out-of-range access (array of seiseki [100]).

    For example, when high = 100 and'seiseki [99] .bango The final result is low = 101 (low = (100 + 99)/2 + 1 = 100 ...), high = 100, and could be i = 100.
    You will end up accessing seiseki [100] .bango.

    Therefore, with high = 99, low = 100, high = 99 =>i = (100 + 99)/2 = 99
    Isn't it necessary to eliminate out-of-range access?