C#の指数演算子がないことは、計算ソフトウェアを古き良きvb6から変換するための新しい言語を探すときに私たちにとって大きな悩みの種でした。
C#を使用してよかったのですが、指数を含む複雑な方程式を書いているときはいつでも、それでもイライラします。このMath.Pow()
方法では、方程式をIMOで読み取るのが非常に困難になります。
DoubleX
私たちの解決策は、-operatorをオーバーライドする特別なクラスを作成することでした^
(以下を参照)
少なくとも1つの変数を次のように宣言する限り、これはかなりうまく機能しますDoubleX
。
DoubleX a = 2;
DoubleX b = 3;
Console.WriteLine($"a = {a}, b = {b}, a^b = {a ^ b}");
または、標準のdoubleで明示的なコンバーターを使用します。
double c = 2;
double d = 3;
Console.WriteLine($"c = {c}, d = {d}, c^d = {c ^ (DoubleX)d}"); // Need explicit converter
ただし、この方法の問題の1つは、指数が他の演算子と比較して間違った順序で計算されることです。これは、操作の周りに常に余分なものを配置することで回避できます。これにより(
)
、方程式を読むのが少し難しくなります。
DoubleX a = 2;
DoubleX b = 3;
Console.WriteLine($"a = {a}, b = {b}, 3+a^b = {3 + a ^ b}"); // Wrong result
Console.WriteLine($"a = {a}, b = {b}, 3+a^b = {3 + (a ^ b)}"); // Correct result
これが、コードで多くの複雑な方程式を使用している他の人の助けになることを願っています。おそらく、誰かがこの方法を改善する方法についてのアイデアさえ持っているでしょうか。
DoubleX
クラス:
using System;
namespace ExponentialOperator
{
/// <summary>
/// Double class that uses ^ as exponential operator
/// </summary>
public class DoubleX
{
#region ---------------- Fields ----------------
private readonly double _value;
#endregion ------------- Fields ----------------
#region -------------- Properties --------------
public double Value
{
get { return _value; }
}
#endregion ----------- Properties --------------
#region ------------- Constructors -------------
public DoubleX(double value)
{
_value = value;
}
public DoubleX(int value)
{
_value = Convert.ToDouble(value);
}
#endregion ---------- Constructors -------------
#region --------------- Methods ----------------
public override string ToString()
{
return _value.ToString();
}
#endregion ------------ Methods ----------------
#region -------------- Operators ---------------
// Change the ^ operator to be used for exponents.
public static DoubleX operator ^(DoubleX value, DoubleX exponent)
{
return Math.Pow(value, exponent);
}
public static DoubleX operator ^(DoubleX value, double exponent)
{
return Math.Pow(value, exponent);
}
public static DoubleX operator ^(double value, DoubleX exponent)
{
return Math.Pow(value, exponent);
}
public static DoubleX operator ^(DoubleX value, int exponent)
{
return Math.Pow(value, exponent);
}
#endregion ----------- Operators ---------------
#region -------------- Converters --------------
// Allow implicit convertion
public static implicit operator DoubleX(double value)
{
return new DoubleX(value);
}
public static implicit operator DoubleX(int value)
{
return new DoubleX(value);
}
public static implicit operator Double(DoubleX value)
{
return value._value;
}
#endregion ----------- Converters --------------
}
}