在c#中计算百分比

本文关键字:百分比 计算 | 更新日期: 2023-09-27 18:09:13

我开始学习c#,这里是一个计算百分比的程序使用系统;

namespace CheckDegree
{
    class Program
    {
        static void Main(string[] args)
        {
            int totalmarks=0;
            for (int i = 0; i < 5;  i++ ) {
            Console.WriteLine("Please enter a subject.");
            string subject = Console.ReadLine();
            Console.WriteLine("Enter the mark for {0}",subject);
            int mark = Convert.ToInt32(Console.ReadLine());
            totalmarks = totalmarks + mark;
            }
            double percentage = (totalmarks / 500) * 100; 
            if (percentage >= 60)
            {
                Console.WriteLine("You got {0} and has been awarded a first division", percentage );
            }
            else if (percentage >= 50 && percentage <= 59)
            {
                Console.WriteLine("You got {0} and has been awarded a second division", percentage);
            } 
            else if (percentage < 40 )
            {
                Console.WriteLine("You got {0} and thus have failed!!!", percentage);
            }
            Console.ReadKey();
        }
    }
}

但是percentage总是输出0

double percentage = (totalmarks / 500) * 100;  

在c#中计算百分比

不是除以500,而是除以500.0。它把它当作一个整数除以一个整数,也就是0 #####。因为它是整数,所以小数点被省略了。那么0乘以100还是0。

将500更改为500.0将强制除法为双精度,这将保留您的十进制值