您是否知道如何解决菜单选择1的功能?
我只为第一个菜单选择而苦苦挣扎,其他所有东西都在起作用。
#include <stdio.h>
#include <stdlib.h>
#define MAXN 100
int menu(){
printf("WELCOME TO C-PROGRAM WORKING WITH NUMBERS\n");
printf("> 1- Input numbers (until 0 is given)\n");
printf("> 2- Print numbers in orginal order\n");
printf("> 3- Search a given number\n");
printf("> 4- Calculate the total between two given numbers\n");
printf("> 5- Print numbers in ascending order\n");
printf("> 6- Quit\n");
printf("Select: ");
int choice;
scanf("%d", &choice);
return choice;
}
int isFul (int*a, int n){
return n==MAXN;
}
int isEmpty (int*a, int n){
return n==0;
}
int inputNumberArray (int a[])
{
int x;
int n=0;
do{
scanf("%d",&x);
a[n]=x;
n=n+1;
}
while (a!=0);
n=n-1;
return n;
}
int search(int x, int *a, int n){
int i;
for (i=0; i<n; i++) if (a[i]==x) return i;
return -1;
}
void printarray(int*a, int n){
int i;
for (i=0;i<n;i++) printf("Result: %d\n", a[i]);
}
void printAsc(int*a, int n){
int** adds =(int**)calloc(n, sizeof(int*));
int i,j;
for(i=0; i<n; i++) adds[i]= &a[i];
int* t;
for (i=0;i<n-1; i++)
for(j=n-1; j>i; j--)
if (*adds[j]< *adds[j-i]){
t=adds[j];
adds[j]=adds[j-1];
adds[j-1]=t;
}
for (i=0;i<n; i++) printf("Result: %d \n", *adds[i]);
free(adds);
}
int sumArray (int a[],int n)
{
int i=0,s=0;
for (i=0;i<n;i++)
{
s=s+a[i];
}
return s;
}
int main(){
int a[MAXN];
int n=0;
char c;
int value;
int choice;
do
{
do
{ choice= menu();
switch(choice){
case 1:{
if (isFul(a,n)) printf("\n Sorry! The numbers is full.\n");
else{
n=inputNumberArray(a);
printf("Added!\n");
}
break;
}
case 3:{
if (isEmpty(a,n)) printf("\n Sorry! No number found!.\n");
else {
printf ("Input the searched value:");
scanf("%d", &value);
int pos = search(value, a, n);
if (pos<0) printf("Not found!\n");
else printf("Postion is found: %d\n", pos);
} break;
}
case 2:{
if (isEmpty(a,n)) printf("\n Sorry! No number found!.\n");
else
{
printarray(a,n);
} break;
}
case 4:{
if (isEmpty(a,n)) printf("\n Sorry! No number found!.\n");
printf("Result: %d",sumArray(a,n));
break;
}
case 5:{
if (isEmpty(a,n)) printf("\n Sorry! No number found!.\n");
else
{
printAsc(a,n);
} break;
}
default: printf ("Goodbye!");
break;
}
} while (choice>0 && choice<6);
printf("Try again?(Y/N)"); scanf("%c",&c);
} while (c=='Y'||c=='y');
if (c=='N'||c=='n') printf("Program ended!");
getchar();
return 0;
}
我的代码如上。我尝试了很多次,但是函数#1似乎不起作用,它只是使整个代码冻结。当应用程序启动时,我按1并保持不变,什么也没有发生。有什么方法可以解决此问题,也可以替换菜单表中的第一名吗?
答案 0 :(得分:1)
您在函数inputNumberArray()
中创建了一个无限循环
int inputNumberArray (int a[])
{
int x;
int n=0;
do{
scanf("%d",&x);
a[n]=x;
n=n+1;
}
while (a!=0); /* This checks if the pointer (array address) a is not a NULL pointer */
n=n-1;
return n;
}
将循环条件更改为
do{
/* ... */
}
while (a[n]!=0); /* This checks if the previously entered number is not 0 */
请注意,如果您输入0作为第一个数字,则此函数将返回-1
。
顺便说一句:当您使用C而不是C ++时,应将没有参数的函数写为returntype function(void)
而不是returntype function()
。