[英]If-Else statements c#
我必須獲取2個矩形的長度和寬度。 確定矩形1是否大於或小於矩形2來確定它們是否具有相同的面積。當我測試此代碼時,無論我輸入什么值,響應都是面積不相同時它們是相同的是。
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");
}
}
}
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和2都等於0。
您進行呼叫的順序將導致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(),以使控制台不會立即關閉並且您可以閱讀消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.