Java编程:计算平均值、最值及构建循环条件
1. 计算平均值
计算平均值是累加和计数的组合操作。我们通过累加来计算总和,通过计数来统计参与求平均值的项目数量。以下是计算平均值的伪代码:
set total to 0
set count to 0
read a number
while the number is not the sentinel value
{
add the number to total
add 1 to the count
read the next number
}
set the average to total / count
output the average
例如,要计算班级的平均考试成绩,我们需要先计算所有考试成绩的总和,然后除以参加考试的学生人数。公式为: average = total / count 。
需要注意的是,如果我们将 total 和 count 声明为整数类型,那么计算平均值时将使用整数除法,这会截断余数。为了得到浮点数平均值,我们需要将其中一个变量( total 或 count )强制转换为 double 或 float 类型,以执行浮点数除法。示例代码如下:
double average =
超级会员免费看
订阅专栏 解锁全文
5万+

被折叠的 条评论
为什么被折叠?



