C# 根据当前值 和 目标值 计算返回最终百分比
以下是计算百分比的C#代码:
double currentValue = 20; // 当前值
double targetValue = 50; // 目标值
double percentage = currentValue / targetValue * 100; // 计算百分比
Console.WriteLine($"当前值 {currentValue} 和目标值 {targetValue}的百分比为: {percentage}%");
输出结果:
当前值 20 和目标值 50的百分比为: 40%
如果想要保留小数点后两位,可以使用以下代码:
double currentValue = 20; // 当前值
double targetValue = 50; // 目标值
double percentage = Math.Round(currentValue / targetValue * 100, 2); // 计算百分比并保留两位小数
Console.WriteLine($"当前值 {currentValue} 和目标值 {targetValue}的百分比为: {percentage}%");
输出结果:
当前值 20 和目标值 50的百分比为: 40%
``
原文地址: https://www.cveoy.top/t/topic/gJt0 著作权归作者所有。请勿转载和采集!