所以我有一个代码,我让用户输入你想比较多少个数字:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(void){
    int n;
    int x;
    int numbers[n];
    int count;

    printf("Mitme arvu vahel soovite võrdlust sooritada?: ");
    scanf("%d",&n);
    printf("Soovisite võrdlust teostada %d arvu vahel\n",n);
    printf("Sisestage palun arvud: \n");
    for (count = 1; count <= n; count++ ){
        printf("Arv %d:",count);
        scanf("%d",&numbers[n]);
        }
    for (count = 0; count <= n; count++){
        if (numbers[count] > x){
            x = numbers[count];
            }
        }
    printf("%d\n",x);
    return 0;
    }

现在的问题是,当最终的printf打印出来时,我得到了某种不切实际的数字。
这是我做n 3时的输出:
./ComparingC Mitme arvu vahel soovite võrdlust sooritada?: 3
Soovisite võrdlust teostada 3 arvu vahel
Sisestage palun arvud:
Arv 1:1
Arv 2:2
Arv 3:3
4196269

最后的数字就是我所说的。它应该在所有其他数字中显示出最大的数字,但现在它显示出一些似乎是从深空出来的东西。
编辑:当我把n设为5,输入1作为第一个数字时,程序就在那里结束了?

最佳答案

这就是你想要的。

#include <stdio.h>
#include <stdlib.h>

int main(void){
    int n;
    int x = 0;
    int* numbers=NULL;
    int count;

    printf("Mitme arvu vahel soovite võrdlust sooritada?: ");
    scanf("%d",&n);
    printf("Soovisite võrdlust teostada %d arvu vahel\n",n);

    numbers = malloc(sizeof(int) * n);
    if(numbers == NULL)
         return -1;

    printf("Sisestage palun arvud: \n");
    for (count = 0; count < n; count++ ){
        printf("Arv %d:",count+1);
        scanf("%d",&numbers[count]);
        }
    for (count = 0; count <= n; count++){
        if (numbers[count] > x){
            x = numbers[count];
            }
        }
    printf("%d\n",x);
    return 0;
    }

在你的机器上运行它,找出你的代码中的错误并学习。

07-24 09:44
查看更多