开发者

Convert the ada code to its C

I have a piece of ada code shown below which is a simple switch case statements.Is there any better way to convert this into C.

         for I in 1..100 loop
           case I is
                when 100 =>
                    Dollars := Dollars + 1;
          开发者_高级运维      when 25|50|75 =>
                    Quarters := Quarters + 1;
                when 10|20|30|40|60|70|80|90 =>
                    Dimes := Dimes + 1;
                when 5|15|35|45|55|65|85|95 =>
                    Nickles := Nickles + 1;
                when others =>
                    Pennies := Pennies + 1;
           end case;
         end loop;

Now by adding the switch and the case for each values in the case,i can do that conversion,But it seems tyo make the code too big.Is there anywa other simple and compact way.Please get back to me if the question is not clear?


Try:

for(i=1;i<=100;i++) {
    if(i == 100) {
        dollars++;
    }else if(i % 25 == 0) {
        quarters ++;
    }else if(i % 10 == 0) {
        dimes ++;
    }else if(i % 5 == 0) {
        nickles ++;
    }else{
        pennies ++;
    }
}


case 100:
    ++Dollars;
    break;
case 25: case 50: case 75:
    ++Quarters;
    break;
case 10: case 20: case 30: case 40: case 60: case 70: case 80: case 90:
    ++Dimes;
    break;
// ...

Not quite as pretty, but still efficient. If performance is at a premium, you'll want to compare the efficiency of this with @unicornaddict's answer, which is cleaner than mine.


for (i = 1; i <= 100; i++)
{

    if (i == 100)
    {
        Dollars++;
    }
    else if (i % 25 == 0)
    {
        Quarters++;
    }
    else if (i % 10 == 0)
    {
        Dimes++;
    }
    else if (i % 5 == 0)
    {
        Nickles++;
    }
    else
    {
        Pennies++;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜