试图了解为什么我的计算失败 [英] Trying to understand why my calculation fails

查看:65
本文介绍了试图了解为什么我的计算失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程的新手,试图理解void方法为何如此有效.在下面的示例中,在控制台中显示了获得的标记,而百分比未显示.

I am new to programming and trying to understand why the void method works as it does. In the below example, obtainedMarks is displayed in the console while percentage does not.

class Student
    {
        string name;
        int age;
        int marksOfMath;
        int marksOfEnglish;
        int marksOfScience;
        int totalMarks = 300;
        int obtainedMarks;
        double percentage;

        void CalculateTotalMarks()
        {
            obtainedMarks = marksOfMath + marksOfEnglish + marksOfScience;
        }

        void CalculatePercentage()
        {
            percentage = obtainedMarks / totalMarks * 100;
        }

        static void Main()
        {
            Student st1 = new Student();
            st1.name = "x";
            st1.age = 20;
            st1.marksOfEnglish = 80;
            st1.marksOfMath = 99;
            st1.marksOfScience = 96;
            st1.CalculateTotalMarks();
            st1.CalculatePercentage();

            Console.WriteLine("{0} of {1} years age got {2}% marks, {3}", st1.name, st1.age, st1.percentage, st1.obtainedMarks);
        }



如果我将"void CalculatePercentage()"更改为此:



If I change the "void CalculatePercentage()" to this:

void CalculatePercentage()
        {
            percentage = obtainedMarks + totalMarks + 100;
        }


百分比现在显示在控制台中.有人能启发我为什么第一次计算应该给我91.67%的时候给我0吗?

预先感谢您的帮助.


percentage is now displayed in the console. Could anybody enlighten me as to why the first calculation gives me 0 when it should give me 91.67%?

Thanks in advance for your help.

推荐答案

答案是,您正在执行的计算不是您认为正在执行的计算.这是给您的一个问题-将275除以300会得到什么?答案不是您所期望的0.91666-实际上是0,所以0 * 100 =0.

我知道这似乎是错误的,但是我在这里将两个整数相除,结果为0.您要执行的操作是将275除为浮点数.幸运的是,有一个快速修复方法.将计算结果更改为
The answer is that the calculation you are performing is not the calculation you think you are performing. Here''s a question for you - what do you get when you divide 275 by 300? The answer is not 0.91666 as you are expecting - it''s actually 0, so 0 * 100 = 0.

I know this seems wrong, but I''ve divided two integers here, and the result is 0. What you are trying to do is divide 275 as a floating point number. Fortunately there''s a quick fix. Change this calculation to be
percentage = (double)obtainedMarks / totalMarks * 100;

现在,当您运行它时,您会得到期望的答案.

Now when you run it, you get the answer you are expecting.


尝试一下...

try this...

percentage = ((double)obtainedMarks / (double)totalMarks) * 100.0;


或在C#中
Or in C#
percentage = (Convert.ToDouble(obtainedMarks) / totalMarks) * 100.0;


这篇关于试图了解为什么我的计算失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆