代码用于将整数扫描到数组中,循环是在输入0时停止扫描。 在以数组内部的最高和最低值扫描值之后,将找到它 找到高和低后,打印高低值数组索引之间的值
所以如果输入5,2,8,7,6,12,6,4,5 输出应为2,7,6,12
我的程序在扫描输入值后失败,输入0是为了结束循环
#include <stdio.h>
int main(){
int high=4;
int low,i;
int array[25];
int count=0;
printf("Please input numbers for array:");
for(i=0;array[i]!=0;i+=1){
scanf("%d",&array[i]);
count+=1;
}
for(i=0;i<count;i+=1){
if(array[i]>array[high]){
high=i;
}
}
low=high;
for(i=0;i<count;i+=1){
if(array[i]<array[low]){
low=i;
}
}
for(i=low;low<=high;i+=1){
printf("%d,",array[i]);
}
}
答案 0 :(得分:1)
for循环在每次迭代之前检查条件,所以在
中 array[i]!=0
在读取数组[i]之前,您正在检查未初始化的值。如果在内存中某处找不到零值,那么这可以继续读取超过25个值,它甚至可以继续运行直到出现堆栈溢出。
另外,在其他for循环中,你可能意味着
i < count
条件
low<high
真的不合适。
这是一个应该更像预期的版本:
#include <stdio.h>
int main(){
int high;
int low,i;
int array[25];
int count=0;
int start;
int end;
printf("Please input numbers for array:");
for (i = 0; scanf("%d", &array[i]), array[i] != 0; i += 1) {
count+=1;
if (i >= 25) {
printf("Unable to handle more than 25 input values\n");
break;
}
}
high = 0;
for (i = 1; i < count; i += 1) {
if (array[i] > array[high]) {
high = i;
}
}
low = 0;
for (i = 1; i < count; i += 1) {
if (array[i] < array[low]) {
low=i;
}
}
if (low < high) {
start = low;
end = high;
}
else {
start = high;
end = low;
}
for (i = start; i <= end; i += 1) {
printf("%d", array[i]);
if (i != end) {
printf(",");
}
else {
printf("\n");
}
}
}
答案 1 :(得分:0)
#include <stdio.h>
int main(){
int low, high, array[25];
int i, count=0;
printf("Please input numbers for array:");
for(i=0;i<25;++i){
int data;
scanf("%d", &data);
if(data==0)
break;
array[count++]=data;
}
low = high = 0;
for(i=1;i<count;++i){
if(array[i]<array[low])
low=i;
if(array[i]>array[high])
high=i;
}
for(i=low;i <= high;i++){
printf("%d,", array[i]);
}
}
答案 2 :(得分:0)
我的代码在经过一些小的更改后正常工作
#include <stdio.h>
int main()
{
int high=0; // high value assumed to be zero for ease of understanding
int low=0,i; // low value assumed to be zero for ease of understanding
int array[25];
int count=0;
printf("Please input numbers for array:");
for(i=0;;i+=1){
scanf("%d",&array[i]);
count+=1;
if(array[i]==0) // Whenever is zero is read the loop is immediately exited, otherwise looping is continued
break;
}
count--; // decrement one count (count of zero)
for(i=1;i<count;i+=1){
if(array[i]>array[high]){
high=i;
}
}
for(i=1;i<count;i+=1){
if(array[i]<array[low]){
low=i;
}
}
for(i=low;i<=high;i+=1){ //printing from low value upto high value
printf("%d,",array[i]);
}
}