公制Convertions算法,而不与QUOT;如果其他"或QUOT;开关情况和QUOT; [英] Metric Convertions Algorithm without "if-else" or "switch-case"

查看:146
本文介绍了公制Convertions算法,而不与QUOT;如果其他"或QUOT;开关情况和QUOT;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个程序,它可以在一个单位转换为另一个单位。比方说,我有2个方法。首先方法可以做的公制转换,第二个方法可以做到体重conversitons 。例如;

I want to write a program which can converts one unit to another unit. Let's say I have 2 methods.First method can do metric conversions, second method can do weight conversitons. For example;

1 长公里= metricConvLength(长密,Enum.mil,Enum.km); //第一种方式

2 长agirlik = metricConvWeight(长公斤,Enum.mil,Enum.km); //第二种方式

我要使用枚举结构这些变量。 我的程序可以将这些东西和对立;

I want to use Enum struct for these variables. My program can convert these things and opposites;

  • 在海里公里
  • 在海里英里
  • feet-公里
  • feet- MIL
  • pound-公斤
  • ons-克
  • INC - 厘米
  • 在院子里 - 米
  • knot-公里

我的问题:我不想使用的if-else 的switch-case 结构的转换。(因为如果我使用的if-else结构,我的code看起来那么糟糕,更容易和slow.And我需要更多的则50的if-else结构,如果我使用这些struct.This时被磨。)

My Question: I don't want to use if-else or switch-case structs for conversions.(Because if I use if-else struct,my code looks like so bad, much easy and slow.And I need more then 50 if-else struct when if I use these struct.This is grind.)

我可以写一个算法,这些转换,而无需使用if-else语句或开关的情况下。的 我的目的是少code,更多的工作。关于算法的任何提示?

Can I write an algorithm for these conversions without using if-else or switch-case. My purpose is less code, more work. Any tips about algorithm?

推荐答案

您不需要 IF-THEN-ELSE - 其实,你并不需要控制语句在你的程序。所有你需要的是一个查找表 - 地图的转换您的设备枚举到转换系数,这样相乘在单位的转换因子,你获得的空间单位米,公斤体重为单位的措施。相反地​​,通过这个因素划分米,方便您所需的单位。

You do not need an if-then-else - in fact, you do not need control statements in your program. All you need is a lookup table - a Map that translates your unit enum to a double conversion factor, such that multiplying the measure in units by the conversion factor you get meters for units of space, and kilos for units of weight. Conversely, dividing meters by that factor gives you the desired units.

通过此地图在手,你可以为所有对单位做转换:

With this map in hand, you can do conversions for all pairs of units:

  • 查找转换系数为源单位
  • 查找转换系数对目标单位
  • 返回值* CS /镉为你的结果。
  • Look up the conversion factor Cs for the source units
  • Look up the conversion factor Cd for the destination units
  • Return value * Cs / Cd as your result.

例如,假设你要处理的米,码,英寸和脚。你的地图是这样的:

For example, let's say that you want to deal with meters, yards, inches, and feet. Your map would look like this:

  • 米 - 1.0
  • Ÿ - 0.9144
  • 在 - 0.0254
  • 在FT - 0.3048

现在让我们假设你要转换 7.5 码到脚:

Now let's say you want to convert 7.5 yards to feet:

  • 查找 CS = 0.9144
  • 查找 CD = 0.3048
  • 计算并返回 RES = 7.5 * 0.9144 / 0.3048 = 22.5
  • Look up Cs = 0.9144
  • Look up Cd = 0.3048
  • Compute and return Res = 7.5 * 0.9144 / 0.3048 = 22.5

这篇关于公制Convertions算法,而不与QUOT;如果其他"或QUOT;开关情况和QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆