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

C#股票涨跌幅计算未显示正确负数结果,求修正方法

股票涨跌幅计算结果异常的修复方案

问题根源是整数除法的截断特性:代码中所有变量均为int类型,执行(newPrice - oldPrice)/Math.Abs(oldPrice)时,-50除以100的实际结果是-0.5,但整数除法会直接舍弃小数部分,得到0,再乘以100后结果仍为0。你的公式逻辑本身是正确的,只需调整数据类型或计算顺序即可修复。

修复方案

  • 方案一:使用浮点类型进行计算(推荐,避免溢出风险)
    将计算过程中的操作数转换为double或float,触发浮点除法保留小数部分,最后可按需转回整数:

    int newPrice = 50;
    int oldPrice = 100;
    // 转为整数结果(如-50)
    int calc = (int)(((double)(newPrice - oldPrice) / Math.Abs(oldPrice)) * 100);
    // 保留小数的结果(如-50.0)
    double calcWithDecimal = ((double)(newPrice - oldPrice) / Math.Abs(oldPrice)) * 100;
    
  • 方案二:调整计算顺序(注意溢出风险)
    先执行乘法再做除法,避免早期的小数截断,但要注意int类型的取值范围,当价格差值过大时可能触发溢出:

    int newPrice = 50;
    int oldPrice = 100;
    int calc = ((newPrice - oldPrice) * 100) / Math.Abs(oldPrice);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:10:40