我在寫一個計算勢能變化的複雜程序(ΔPE=mgΔh)。如何交換兩個變量值?
Console.WriteLine("Mass in kg");
string cmMa = Console.ReadLine();
double cMass;
if(!Double.TryParse(cmMa, out cMass))
{
Console.WriteLine("Only numbers!");
Console.ReadLine();
}
Console.WriteLine("First height in m");
string cfH = Console.ReadLine();
double fH;
if(!Double.TryParse(cfH, out fH))
{
Console.WriteLine("Only numbers!");
Console.ReadLine();
}
Console.WriteLine("Second height in m");
string csH = Console.ReadLine();
double sH;
if(!Double.TryParse(csH, out sH))
{
Console.WriteLine("Only numbers!");
Console.ReadLine();
}
double ch = fH - sH;
Console.WriteLine("Intermediate result: Change in height(Δh)= "+ch+" m");
Console.ReadLine();
double ng = 9.81; // m/s^2
Console.WriteLine("CHANGE IN POTENTIAL ENERGY: "+ch*cMass*ng+" J");
最後,我想添加一個if語句,如果sH> fH,那麼它們的值被交換。我應該申請什麼概念?
很平凡:使用第三個變量。這裏沒有概念。 –
'double ch = Math.Abs(fH - sH);' – Ryan
[不使用臨時變量交換兩個變量]的可能重複(http://stackoverflow.com/questions/804706/swap-two-variables-without-使用溫度變量) –