Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

C 数组 - 实战示例


实战示例

为了演示使用数组的实际示例,让我们创建一个计算不同年龄平均值的程序。

示例

// 存储不同年龄的数组
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};

float avg, sum = 0;
int i;

// 获取数组的长度
int length = sizeof(ages) / sizeof(ages[0]);

// 遍历数组元素
for (i = 0; i < length; i++) {
  sum += ages[i];
}

// 用总和除以长度来计算平均值
avg = sum / length;

// 打印平均值
printf("The average age is: %.2f", avg);
自己试一试 »

在这个示例中,我们创建一个程序来查找不同年龄中最小的年龄。

示例

// 存储不同年龄的数组
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};

int i;

// 获取数组的长度
int length = sizeof(ages) / sizeof(ages[0]);

// 创建一个变量,并将 ages 数组的第一个元素赋给它
int lowestAge = ages[0];

// 遍历 ages 数组的元素,查找最小年龄
for (i = 0; i < length; i++) {
  if (lowestAge > ages[i]) {
    lowestAge = ages[i];
  }
}
自己试一试 »


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.