我如何在C ++中执行以前执行的代码行

问题描述 投票:0回答:2

我已经开始在业余时间使用其他也从网上学过C ++的人提供给我的网站和应用程序学习如何用C ++进行编码。到目前为止,我知道最基本的命令。我已经尝试过某个程序提供的锻炼,而且得到的信息是某人正在度假,并且需要知道他可以带多少行李。他最多只能携带45个行李,如果行李低于,超过或等于限制(45个行李),我必须显示不同的输出。我已经完成了一些编码,最终得到了这个:

#include <iostream>

using namespace std;

int main()
{
    const int limit = 45;
    int bag;
    cout << "Please type your number here: ";
    cin >> bag;
    string yn;
    int keep = 0;
    if (limit < bag)
    {
        cout << "You passed the limit." << endl;
    };
    if (limit == bag)
    {
        cout << "Just enough." << endl;
    };
    if (limit > bag)
    {
        cout << "You got space." << endl;
    };
    ++keep;
    while(keep > 0)
    {
        int keep = 0;
        cout << "Do you want to try another number?" << endl;
        cin >> yn;
        cout << endl;
        if(yn == "yes")
        {
            int bag = 0;
            cout << "Please type your number here: ";
            cin >> bag;
            if (limit < bag)
            {
                cout << "You passed the limit." << endl;
            };
            if (limit == bag)
            {
                cout << "Just enough." << endl;
            };
            if (limit > bag)
            {
                cout << "You got space." << endl;
            };
        }
        else
        {
            return 0;
        }
    }
}

正如您所看到的,出于对问题的我自己的兴趣,我已经开发了超出需要的功能。我已经复制并粘贴了如上所示的3个IF命令,并且我相信有一种更简单的方法,只需更少的代码即可解决此问题。我想到的是我是否可以返回并再次执行某些代码行,无论是从一行或以下(例如从第45行及以下),还是特定的代码行(例如从第45行至第60行)。如果您想到了另一种方法来解决此问题并将代码发布在下面,将不胜感激。谢谢您的答复。

c++ c++11 if-statement conditional-statements c++17
2个回答
0
投票

您可以简单地运行while循环并执行以下操作:

#include <iostream>
using namespace std;

int main()
{
    const int limit = 45;
    int bag;
    string yn = "yes";
    while(yn == "yes")
    {
        cout << "Please type your number here: ";
        cin >> bag;
        if (limit < bag)
        {
            cout << "You passed the limit." << endl;
        }
        else if (limit == bag)
        {
            cout << "Just enough." << endl;
        }
        else if (limit > bag)
        {
            cout << "You got space." << endl;
        }
        cout << "Do you want to try another number?" << endl;
        cin >> yn;
        cout << endl;
    }
}

1
投票

我们都从某个时候开始编写我们的第一个C ++程序,所以让我给您一些其他反馈:

  • 首先,avoid writing using namespace std;
  • 第二,命名-什么是using namespace std;baglimitkeep?读取和理解它们分别为ynbagSizemaximumPermittedBagSize会不会容易得多(您实际上并不需要变量inputFromUser,请参见下文)?
  • 最后,这是程序的(大致)重构版本,其中删除了重复项并添加了注释。
keep
© www.soinside.com 2019 - 2024. All rights reserved.