You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java如何实现每300米沸点减1度的循环,根据温度海拔判断水状态

代码修改方案

首先你要的沸点计算逻辑有两种实现方式,优先推荐用整除运算,性能更高也更简洁,如果一定要用循环实现也提供对应写法:

1. 整除实现(推荐)

每满300米减1度的需求本质是求海拔包含多少个完整的300米,直接用整数整除就能实现,完整修改后的代码如下:

import java.util.Scanner;
public class WaterState
{
    public static void main(String[]args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the temperature then the altitude separated by one or more spaces");
        double temperature = scan.nextDouble();
        double altitude = scan.nextDouble();
        // 计算当前海拔对应的沸点
        int decrease = (int)(altitude / 300);
        double bp = 100 - decrease;
        
        if (temperature <= 0)
        {
            System.out.println ("Water is solid at the given conditions");
        }
        else if (temperature > 0 && temperature < bp)
        {
            System.out.println ("Water is liquid at the given conditions");
        }
        else
        {
            System.out.println ("Water is gas at the given conditions");
        }
        scan.close();
    }
}

这里把altitude / 300的结果强转为int会自动舍去小数部分,刚好满足只有满300米才减1度的要求,比如海拔700米时700/300≈2.33,强转后得到2,沸点就是98度,符合规则。同时把原来的三个独立if改成了if-else结构,避免临界值重复判断的问题。

2. 循环实现

如果你需要用循环逻辑完成计算,可以用以下代码替换沸点计算部分:

double bp = 100;
double remainingAlt = altitude;
// 每满300米沸点减1度
while (remainingAlt >= 300) {
    bp -= 1;
    remainingAlt -= 300;
}

循环逻辑非常直观:每次判断剩余海拔是否达到300米,达到就把沸点减1,同时扣掉已经计算过的300米,直到剩余海拔不足300米为止,和你要的逻辑完全匹配。

内容的提问来源于stack exchange,提问作者emily

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 13:39:03