This question already has answers here:
What will be the value of uninitialized variable? [duplicate]
                                
                                    (6个答案)
                                
                        
                        
                            (Why) is using an uninitialized variable undefined behavior?
                                
                                    (7个答案)
                                
                        
                                2年前关闭。
            
                    
源代码:

int main(void) {

    double values[10];
    int size = 5;
    double max_val = values[0];
    double min_val = values[0];

    printf("Enter 10 double values for the array\n");
    for (int i = 0; i < size; i++) {
        scanf("%lf", &values[i]);
    }

    for (int x = 0; x < size; x++) {
        if (values[x] > max_val) {
            max_val = values[x];
        }
        if (values[x] < min_val) {
            min_val = values[x];
        }
    }

    printf("Maximum value: %.2lf\n", max_val);
    printf("Miniimum value: %.2lf\n", min_val);
    return 0;

}


输入数组的10个双精度值

10.4
56.7
21.1
0.3
4.8


Maximum value: 56.70
Minimum value: -92559631349317830736831783200707727132248687965119994463780864.00

最佳答案

double max_val = values[0];
double min_val = values[0];


您已为max_val和min_val分配了垃圾值,因为此时尚未为values [0]分配任何值

在for循环中输入后,应移动此分配

关于c - 为什么我的最小值显示一些垃圾值? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45558691/

10-09 08:58