我必须获得2个矩形的长度和宽度。如果矩形1大于或小于矩形2,则确定它们是否具有相同的区域。当我测试此代码时,无论我放入什么值,响应是当它们不应该是#39时区域是相同的。 ;是的。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace twoRectangles
{
class Program
{
static void Main(string[] args)
{//declare variables and methods
double length = 0.00;
double width = 0.00;
double lengthTwo = 0.00;
double widthTwo = 0.00;
double area1 = length * width;
double area2 = lengthTwo * widthTwo;
getArea1(ref length, ref width);
getArea2(ref lengthTwo, ref widthTwo);
greaterArea(ref area1, ref area2);
}//call method getArea1
static void getArea1(ref double length, ref double width)
{//input for length of first rectangle
Console.WriteLine("Please enter the length of the first rectangle:");
while (!double.TryParse(Console.ReadLine(), out length))
Console.WriteLine("Error, please enter a valid number");
//input for width of frist rectangle
Console.WriteLine("lease enter the width of the first retangle:");
while (!double.TryParse(Console.ReadLine(), out width))
Console.WriteLine("Error, please enter a valid number");
}//call method get Area2
static void getArea2(ref double lengthTwo, ref double widthTwo)
{//input for length of second rectangle
Console.WriteLine("Please enter the length of the second rectangle:");
while (!double.TryParse(Console.ReadLine(), out lengthTwo))
Console.WriteLine("Error, please enter a valid number");
//input for width of second rectangle
Console.WriteLine("Please enter the width of the second rectangle:");
while (!double.TryParse(Console.ReadLine(), out widthTwo))
Console.WriteLine("Error, please enter a valid number");
}//call method greaterArea
static void greaterArea(ref double area1, ref double area2)
{//if statements
if (area1 == area2)
{
Console.WriteLine("The areas of the rectangles are the same");
}
else if(area1 > area2)
{
Console.WriteLine("The area of Rectangle 1 is greater than Rectangle 2");
}
else if(area1 < area2)
{
Console.WriteLine("The area of Rectangle 1 is less than Rectangle 2");
}
}
}
答案 0 :(得分:2)
从顶部到底部逐行执行C#程序。您的问题即将到来,因为您在用户输入尺寸之前计算区域。试试这个:
getArea1(ref length, ref width);
getArea2(ref lengthTwo, ref widthTwo);
double area1 = length * width;
double area2 = lengthTwo * widthTwo;
greaterArea(ref area1, ref area2);
答案 1 :(得分:1)
在获取用户的长度和宽度之前,您正在计算两个矩形的面积。矩形1和2都等于0。
答案 2 :(得分:1)
您拨打电话的顺序导致area1和area2每次都为0。试试这个:
double length = 0.00;
double width = 0.00;
double lengthTwo = 0.00;
double widthTwo = 0.00;
getArea1(ref length, ref width);
getArea2(ref lengthTwo, ref widthTwo);
double area1 = length * width;
double area2 = lengthTwo * widthTwo;
greaterArea(ref area1, ref area2);
Console.ReadKey();
您需要在getArea1()/ getArea2()调用之后初始化area1和area2,以便length,width,lengthTwo和widthTwo具有值。
另外,我建议您在调用greaterArea()之后放置一个Console.ReadKey(),这样控制台就不会立即关闭,您可以阅读该消息。