/ 猿问

# 为什么此浮点计算在不同的计算机上给出不同的结果？

2019-10-21 15:20:15

public string AspectRatioAsString(float f)

{

bool carryon = true;

int index = 0;

double roundedUpValue = 0;

while (carryon)

{

index++;

float upper = index * f;

roundedUpValue = Math.Ceiling(upper);

if (roundedUpValue - upper <= (double)0.1 || index > 20)

{

carryon = false;

}

}

return roundedUpValue + ":" + index;

}

## 3 回答

C＃XNA Visual Studio：“发布”和“调试”模式之间的区别？

CLR JIT优化违反因果关系吗？

struct Ratio

{

public int X { get; private set; }

public int Y { get; private set; }

public Ratio (int x, int y) : this()

{

this.X = x;

this.Y = y;

}

public double AsDouble() { return (double)X / (double)Y; }

}

Ratio[] commonRatios = {

new Ratio(16, 9),

new Ratio(4, 3),

// ... and so on, maybe the few hundred most common ratios here.

// since you are pinning results to be less than 20, there cannot possibly

// be more than a few hundred.

};

public string AspectRatioAsString(double ratio)

var results = from commonRatio in commonRatios

select new {

Ratio = commonRatio,

Diff = Math.Abs(ratio - commonRatio.AsDouble())};

var smallestResult = results.Min(x=>x.Diff);

return String.Format("{0}:{1}", smallestResult.Ratio.X, smallestResult.Ratio.Y);

}

• 32位和64位？

• Windows 7 vs Vista vs XP？

• 英特尔与AMD处理器？（感谢Oded）

(double) 0.1 演员是不必要的。

public string AspectRatioAsString(double ratio)

{

for (int height = 1; height <= 20; ++height)

{

int    width = (int) Math.Round(height * ratio);

double guess = (double) width / height;

if (Math.Abs(guess - ratio) <= 0.01)

{

return width + ":" + height;

}

}

throw ArgumentException("Invalid aspect ratio", "ratio");

}

• 3 回答
• 0 关注
• 272 浏览

0/150