为什么此Area方法返回0? [英] why this Area Method return 0 ?
本文介绍了为什么此Area方法返回0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
using System;
namespace Test
{
class Program
{
static void Main()
{
// in the name of God
// Chapter Inheritance 11
Triangle tr1 = new Triangle();
tr1.Width = 2;
tr1.Height = 3;
tr1.Style = "Style";
Triangle tr2 = new Triangle();
tr2.Width = 4;
tr2.Height = 6;
tr2.Style = " Two Style";
Console.WriteLine(" Info Triangle1");
tr1.ShowD();
Console.WriteLine(" Area:{0}", tr1.Area());
Console.ReadLine();
}
}
class TwoDShape
{
// Fields
public int Width;
public int Height;
// Constructors
// Methods
public void ShowD()
{
Console.WriteLine(" Width:{0}\tHeight:{1}", Width, Height);
}
// Indexers
}
class Triangle : TwoDShape
{
// fields
public string Style;
// Constructors
// Methods
public void ShowS()
{
Console.WriteLine(" Style:{0}", Style);
}
public int Area()
{
return (Width * Height)* (1/2); ????
}
// Indexers
}
}
推荐答案
简单:"1/2"不是您想像的一半-它为零,因为这是整数运算.试试这个:
Simple: "1/2" is not a half as you think - it is zero because this is integer arithmetic. Try this:
public int Area()
{
return (Width * Height) / 2;
}
1和2都是整数Width和Height也是整数.当进行(1/2)中的整数运算时,预期结果确实为零.您可以通过两种方式重写表达式,从而产生略有不同的结果.
这将产生一个整数结果:
1 and 2 are both ints Width and Height are integers as well. When doing integer arithmetic as in (1/2) the expected out come is indeed zero. You can rewrite your expression in two ways yielding slightly different results.
This will yield an integer result:
public int Area()
{
return (Width * Height) / 2;
}
这将产生双重结果:
This will yield a double result:
public double Area()
{
double two = 2.0;
return (double)(Width * Height) / 2;
}
问候,
Regards,
这篇关于为什么此Area方法返回0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文