【问题标题】:Printing only one combination using nested loops使用嵌套循环仅打印一种组合
【发布时间】:2014-11-15 13:07:18
【问题描述】:

我必须打印一个男人应该支付给收银员的不同纸币的组合。程序首先询问要支付的总金额,然后询问他拥有的不同面额的纸币。问题是,我只需要打印一种纸币组合,但我会通过以下代码获得所有组合(像往常一样)。

#include <stdio.h>
int main(void)
{
    int hundred,fifty,ten,total,hund,fif,t;
    printf ("Enter amount to be paid:");
    scanf ("%d",&total);
    printf ("\n\nHow many currency notes do you have?\nEnter 100,50 and 10 Rupee Notes Respectively:\n");
    scanf ("%d %d %d",&hund,&fif,&t);

    printf ("\t\t\tPossible combination for Rs=%d/- \n",total);

    for (hundred=0; hundred<=hund; hundred++)
    {
          for (fifty=0; fifty<=fif; fifty++)
        {
            for (ten=0; ten<=t; ten++)
            {
                if ((hundred*100+fifty*50+ten*10)==total)
                {
                    printf("\n\n Hundred rupees notes=%d, 50 rupees notes=%d, 10 rupees notes=%d",hundred,fifty,ten);
                }
            }
        }
    }
    getch();
    return 0;
}

【问题讨论】:

  • 想一想如何做到没有循环,使用更少的货币
  • printfreturn 0;
  • “代码运行良好”——在清理你的缩进时,我发现了一个流浪者{。请确保您用于显示问题的代码本身是正确的。
  • @Pradheep 我完全没有任何循环。但是我的教练告诉我要尝试嵌套。
  • @AsharNawazKhan ,您可以结束程序或使用我的回答中提到的goto()

标签: c for-loop codeblocks combinations nested-loops


【解决方案1】:

在嵌套循环内的printf 之后添加getch();return 0;

另一种方法是使用goto。输入

goto exit;

就在嵌套循环内的printf 之后并键入

exit:

就在getch();之前。

【讨论】:

    猜你喜欢
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 2015-12-09
    相关资源
    最近更新 更多