[英]program that does not terminate
I wrote a program that should take an array of numbers and find the array index of the smallest number. 我编写了一个程序,该程序应采用数字数组并找到最小数字的数组索引。 However, when I type the numbers with spaces between and then press enter, the program keeps running.
但是,当我键入之间带有空格的数字,然后按Enter键时,程序将继续运行。 What can be the cause?
可能是什么原因? Here is the code:
这是代码:
#include<stdio.h>
//read numbers to an array
//find minimum
//print the index of minimum
double findMinimum(int size,double array[]){
int n;
int minIndex=0;
for(n=1;n<size;size++){
if(array[n]<array[n-1]){
minIndex=n;
}
}
return minIndex;
}
int main(){
setvbuf(stdout,NULL,_IONBF,0);
int size=0;
double inArray[size];
printf("Enter an array of numbers:");
int k=0;
char c;
while(c!='\n'){
c=getchar();
if(c=='\n'){
break;
}
scanf("%lf",&inArray[k]);
k++;
size++;
};
int minIndex=0;
minIndex=findMinimum(size,inArray);
printf("The index of minimum number is %i",minIndex);
return 0;
}
I also took the part of the code that scans numbers to an array. 我还使用了将数字扫描到数组的代码部分。 I tried to change the while loop and used "break" statement, but the output gave all numbers in an array except the first one.
我试图更改while循环,并使用“ break”语句,但是输出给出了除第一个数组以外的所有数字。 Here is the code:
这是代码:
#include<stdio.h>
//read numbers to an array
int main(){
setvbuf(stdout,NULL,_IONBF,0);
int size=0;
double inArray[size];
printf("Enter an array of numbers ending with question mark:\n");
int k=0;
char c;
while(1){
c=getchar();
if(c=='?'){
break;
}
scanf("%lf",&inArray[k]);
k++;
size++;
};
int n;
for(n=0;n<size;n++){
printf("%f\n",inArray[n]);
}
return 0;
}
Thanks for help in advance! 预先感谢您的帮助!
for(n=1;n<size;size++){
if(array[n]<array[n-1]){
minIndex=n;
}
}
The issue in your code is you are incrementing size
, thats why your loop is not terminating. 代码中的问题是您要增加
size
,这就是循环没有终止的原因。 increment n
增量
n
Edit 编辑
you have initialized your 'n' with 1 , however arrays start with zero index thats why it misses the first element, 您已经用1初始化了'n',但是数组以零索引开头,这就是为什么它错过了第一个元素的原因,
for(n=0;n<size;n++){
if(array[n]<array[minIndex]){
minIndex=n;
}
}
try this one : 试试这个:
for(n=1; n < size; n++){
if(array[n]<array[minIndex]){
minIndex=n;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.