我的问题:我不知道如何删除数组中输入的最后一个元素。当用户输入负数时,程序应该停止,并且不应在数组内包含负数。我试过了,但我找不到解决办法。这是我的代码:
int main () {
float array[20];
float max ,min;
float rem;
int i;
char op;
for (i = 0; i <= 20; i++){
printf("Enter the element inside array[%d]: ",i);
scanf("%f", &array[i]);
if (array[i] < 0)
break;
}
printf("Enter ......: ");
scanf("%s", &op);
switch (op){
case 'h':
max = array[0];
for (i = 0; i < 20; i++){
if (max < array[i]){
max = array[i];
}
}
printf("The biggest number is: %f\n", max);
break;
case 'l':
min = array[0];
for (i = 0; i < 20; i++){
if (min > array[i]){
min = array[i];
}
}
printf("The smallest number is: %f\n", min);
break;
}
return 0;
}
请帮助,我没有想法。 非常感谢你。
答案 0 :(得分:1)
在存储到数组中之前,只需检查输入的值:
int main () {
float array[20]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
float max ,min;
float rem;
int i;
float a;
char op;
for (i = 0; i < 20; i++){
printf("Enter the element inside array[%d]: ",i);
scanf("%f", &a);
if (a < 0)
break;
array[i]=a;
}
答案 1 :(得分:1)
之前使用临时变量,如果它是数组中的正存储,如果不采取必要的操作。
for (i = 0; i < 20; i++){
printf("Enter the element inside array[%d]: ",i);
scanf("%f", &x) // declare x as float x;
if (x< 0) // if negative break
break;
array[i]=x; // store into array
}
以及您计划中的一些问题 -
printf("Enter ......: ");
scanf("%s", &op); // op is char variable use %c specifier
^ use instead %c
这样写 -
scanf(" %c", &op);
此第一个循环访问索引超出范围导致 UB
for (i = 0;i<=20; i++){ // change condition to i<20 (index can go from 0 to 19)
//your code // as array is declared as float array[20]
}
max
和min
的循环都可以这样 -
for (i= 0;array[i]; i++){ // no need to keep track of length of array
答案 2 :(得分:1)
我很抱歉我的最后一个答案,但这是真的;)
#include<stdio.h>
int length(const float *array) {
int count = 0;
while(array[count]) count++;
return count;
}
void main () {
float array[20];
float max ,min;
float rem,input;
int i;
char op;
int length = 0;
for (i = 0; i < 20; i++){
printf("Enter the element inside array[%d]: ",i);
scanf("%f", &input);
if (input < 0)
break;
length++;
array[i] = input;
}
printf("Enter ......: ");
scanf(" %c", &op);
switch (op){
case 'h':
max = array[0];
for (i = 0; i < 20; i++){
if (max < array[i]){
max = array[i];
}
}
printf("The biggest number is: %f\n", max);
break;
case 'l':
min = array[0];
for (i = 0; i < length; ++i){
if (min > array[i]){
min = array[i];
}
}
printf("The smallest number is: %f\n", min);
break;
}
system("pause");
}