首页 > 解决方案 > 进程过早退出 C 编程

问题描述

有一部分程序要求用户输入YN,然后当我选择N时循环返回,否则它将结束 while 循环并继续。当我第一次选择Y时,程序可以正常工作,但是当我选择N然后在我的程序退出后选择Y时,即使它没有遇到return来自 main 的关键字并且它以垃圾return值退出。它停在system("cls");。谁能告诉我这段代码有什么问题。注意: Statistician是我用 typedef 创建的整数指针类型。而且,我还在survey.h文件中声明了SIZE 变量

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include "survey.h"

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {

    SIZE = 10;
    int c, count = 0, item = 0;
    Statistician arr;
    float mea, med;

    arr = (int*)calloc(10, sizeof(int));

    printf("Enter 10 answers\n");

    while(count < SIZE) // this is the while loop that loops until Y is chosen by the user in the add function
    {
        while(item > 9 || item < 1)
        {
            scanf("%d", &item);
        }

        ++count;
        add(arr, &count, &SIZE, item);
        item = 0;
    }
    system("cls");
    mea = mean(arr, count);
    med = median(arr, count);
    printf("mean = %f\n", mea);
    printf("median = %f\n", med);

    return 0;
}

功能定义add()

void add(Statistician answer, int *count, int *SIZE, int item)
{

    int i, j, temp;
    bool swapped;
    char choice;
    
    answer[*count - 1] = item;

    for(i = 0; i < *count - 1; i++)
  {
    swapped = false;
    for(j = 0; j < *count - i - 1; j++)
    {

      if(answer[j] > answer[j + 1])
      {
        temp = answer[j];
        answer[j] = answer[j + 1];
        answer[j + 1] = temp;
        swapped = true;
      }

    }

  if(swapped == false)
  break;
  }

  if(*count == *SIZE)
    {
        printf("Array is full do you want to compute now?\n");
        while(toupper(choice) != 'N' && toupper(choice) != 'Y') // The part where the program ask for Y or N.
        {
            choice = toupper(getch());
        }
        if(toupper(choice) == 'Y') // returns without changing the value of SIZE thus ending the while loop at main
        {
            return;
        }
        else if(toupper(choice) == 'N') // adds 10 to SIZE thus continuing the while loop in main and returns
        {
            printf("add another 10 answers\n");
            *SIZE += 10;
            realloc(answer, *SIZE);
        }
    }

    return;
}

标签: creturnmain

解决方案


可能还有其他问题(我不会仔细研究),但您当然需要修复:

   while(item > 9 || item < 1)
    {
        scanf("%d", &item);
    }

如果 scanf 匹配零个项目,那么这是一个无限循环, scanf 重复返回 0,读取相同的数据并且不更改item. 您必须始终检查 scanf 返回的值。


推荐阅读