【发布时间】:2020-12-29 23:28:46
【问题描述】:
有一部分程序要求用户输入 Y 或 N 然后当我选择 N 时循环返回,否则它将结束while循环并继续。当我第一次选择 Y 时,程序运行正常,但是当我选择 N 然后在我的程序退出后选择 Y 时,即使它确实如此没有遇到来自 main 的 return 关键字
它以垃圾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;
}
【问题讨论】:
-
阅读Modern C,查看this C reference,阅读您的C编译器(例如GCC...)和调试器(例如GDB)的文档并使用您的调试器
-
你能说明
Statistician的定义吗? -
在编译时启用所有警告和调试信息。使用GCC,使用
gcc -Wall -Wextra -g进行编译。在您的问题中提供一些minimal reproducible example -
choice第一次使用时未初始化。 -
您是否尝试过在调试器中逐行运行代码,同时监控所有变量的值,以确定您的程序在哪个点停止按预期运行?如果您没有尝试过,那么您可能想阅读以下内容:What is a debugger and how can it help me diagnose problems? 您可能还想阅读以下内容:How to debug small programs?。使用通过调试器获得的信息,您可以创建一个minimal reproducible example 来解决您的问题。