🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# C 程序:使用动态内存分配查找最大数字 > 原文: [https://www.programiz.com/c-programming/examples/dynamic-memory-allocation-largest](https://www.programiz.com/c-programming/examples/dynamic-memory-allocation-largest) #### 在此示例中,您将学习在动态分配的内存中查找用户输入的最大数字。 要理解此示例,您应该了解以下 [C 编程](/c-programming "C tutorial")主题: * [C 指针](/c-programming/c-pointers) * [C 动态内存分配](/c-programming/c-dynamic-memory-allocation) * [C `for`循环](/c-programming/c-for-loop) * * * ## 在动态分配的内存中找到最大的元素 ```c #include <stdio.h> #include <stdlib.h> int main() { int num; float *data; printf("Enter the total number of elements: "); scanf("%d", &num); // Allocating memory for num elements data = (float *)calloc(num, sizeof(float)); if (data == NULL) { printf("Error!!! memory not allocated."); exit(0); } // Storing numbers entered by the user. for (int i = 0; i < num; ++i) { printf("Enter Number %d: ", i + 1); scanf("%f", data + i); } // Finding the largest number for (int i = 1; i < num; ++i) { if (*data < *(data + i)) *data = *(data + i); } printf("Largest number = %.2f", *data); return 0; } ``` **输出** ```c Enter the total number of elements: 5 Enter Number 1: 3.4 Enter Number 2: 2.4 Enter Number 3: -5 Enter Number 4: 24.2 Enter Number 5: 6.7 Largest number = 24.20 ``` 在程序中,要求用户输入元质数,该元质数存储在变量`num`中。 我们将为`num`个浮点值分配内存。 然后,要求用户输入`number`数字。 这些数字存储在动态分配的内存中。 最后,确定这些数字中最大的数字并将其打印在屏幕上。