C# 请问为什么我的代码中三角形的值=0?

C# 请问为什么我的代码中三角形的值=0?,c#,C#,请帮忙看看为什么三角形的值不是15,但在我的代码中是0。 非常感谢。 格本加·奥拉尼佩昆 class Program { static void Main(string[] args) { // int a =3 + 6; // int b = 5 -7; // int a; // a =3 + 6; // b =5 + 7; // int a = 6 // b =c

请帮忙看看为什么三角形的值不是15,但在我的代码中是0。 非常感谢。 格本加·奥拉尼佩昆

class Program
{
    static void Main(string[] args)
    {
        // int a =3 + 6;
        // int b = 5 -7;
        // int a;
        // a =3 + 6;
        // b =5 + 7;
        // int a = 6
        // b =c +5;
        // v = b -j ;
        // double moneymadefromgames = 100000;
        // double totalprogrammers = 4;
        // double moneyperperson = moneymadefromgames / totalprogrammers; 
        // the formular for area of circle is pi * r ^ 2;
        // the formular for area of triagle is 1/2 b * h;
        float b = 5;
        float height = 6;
        double area = 1/2 *b *  height;
        Console.WriteLine("the areas of triagle is " + area);
        int score;
        int age;
        age = -89;
        score = 33;
        int loan;
        int credit;
        float radius = 4;
        float pi = 3.1415926536f; // the 'f' makes it a float literal instead of a double literal.
        float newarea = pi * radius * radius;
        // using the + operator with strings results in "concatenation".
        Console.WriteLine("The area of the circle is " + newarea + ".");
       loan = 2000;
        credit = 5000;
        float totalcost = 22.54F;
        float tipPercent = 0.18F;
        float tipAmount =  totalcost * tipPercent;
        double moneymadefromgames = 100000;
        double totalprogrammers = 4;
        double moneyperperson = moneymadefromgames / totalprogrammers;
        System.Console.WriteLine(moneyperperson);
        System.Console.WriteLine(score - age);
        System.Console.WriteLine("PRESS ANY key to exit");
        System.Console.WriteLine(loan + credit);
        System.Console.WriteLine(tipAmount);
        System.Console.Read();
        
    }
}

需要将1/2值更改为0.5以进行面积计算。所以它应该
双面积=0.5*b*高度。这就是为什么得到的是零而不是实际值


using System;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            float b = 5;
            float height = 6;
            double area = 0.5 *b *  height;
            Console.WriteLine("the areas of triagle is " + area);
        }
    }
}

输出:

三角形的面积是15

这是截图


这里的问题是分工。您要计算
0.5*b*高度
。所以如果你输入0.5而不是1/2,你会得到15

这里发生的是整数除法

对于整数类型的操作数,/运算符的结果为整数类型,等于向零舍入的两个操作数的商

当您将两个整数除时,程序将忽略余数。 由于1/2是0.5,整数除法将返回的所有值都是0,忽略0.5余数。
要解决此问题,您需要通过添加余数使至少一个数字成为浮点/双倍值。
1/2.0
1.0/2
1.0/2.0
。 因此,结果将为0.5

Console.WriteLine(1   / 2  );  // output: 0
Console.WriteLine(1   / 2.0);  // output: 0.5
Console.WriteLine(1.0 / 2  );  // output: 0.5
Console.WriteLine(1.0 / 2.0);  // output: 0.5

解释一下原因可能也会有所帮助
1和
2是整数文本。具有整数左操作数和整数右操作数的
/
运算符将生成一个整数结果,即除法的下限。。。还可以提及其他选项:保持公式不变,但使用浮点文字,即
1f/2f*…
或只需除以表达式末尾的整数值即可。由于您对一次计算有特定的查询,你应该从你的问题中删除不相关的代码,这是在做其他不相关的计算。我想你的意思是1/2,而不是2/1。更改太小,我无法为您编辑。@moreON谢谢,您说得对,我更改了它。