c - 进程过早退出 C 编程
问题描述
有一部分程序要求用户输入Y或N,然后当我选择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;
}
解决方案
可能还有其他问题(我不会仔细研究),但您当然需要修复:
while(item > 9 || item < 1)
{
scanf("%d", &item);
}
如果 scanf 匹配零个项目,那么这是一个无限循环, scanf 重复返回 0,读取相同的数据并且不更改item
. 您必须始终检查 scanf 返回的值。
推荐阅读
- java - 使用流将字符串数组转换为映射
- python - 如何使用 Python 将来自不同公司的多个董事的数据汇总到每个公司使用 Blau 指数的一个数字中?
- sql - 如果所有条件都等于特定值,是否有办法返回与 SQL 中特定字段关联的输出
- python - 简单线程会杀死内核或不按预期运行
- r - 时间序列预测(使用 R)
- javascript - 如何处理角度4中的空异常
- javascript - Firefox 在重新加载时保持更新服务工作者
- php - PHP argv 丢失导致脚本无法运行
- php - 在 wordpress 网站的页面上禁用了滑块。jQuery 在此页面上也被禁用。找出禁用它的最快方法是什么?
- php - 数组减少变量中的返回布尔值