Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/158.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使此函数正确循环_C++_Loops - Fatal编程技术网

C++ 使此函数正确循环

C++ 使此函数正确循环,c++,loops,C++,Loops,我在做一个函数,给出从芝加哥到某个城市的旅行时间。我试着让它循环,这样当用户选择城市时,它会给出所需的时间,并循环回问主要问题,让用户选择另一个城市。我还包括一个选项,他们可以退出循环。到目前为止,我得到的是: main() { TripInfo trip; int choice; do { cout << "You are in Chicago. Where would you like to

我在做一个函数,给出从芝加哥到某个城市的旅行时间。我试着让它循环,这样当用户选择城市时,它会给出所需的时间,并循环回问主要问题,让用户选择另一个城市。我还包括一个选项,他们可以退出循环。到目前为止,我得到的是:

    main()
    {
      TripInfo trip;
      int choice;

      do
        {
          cout << "You are in Chicago. Where would you like to drive?\n"
               << "Enter number of city\n" << "1. New York City\n" << "2. Boston\n"
               << "3. Philadelphia\n" << "4. Toronto\n" << "5. Washington D.C.\n"
               << "6. Miami\n" << "7. Indianapolis\n" << "8. Los Angeles\n"
               << "9. San Fransisco\n" << "10. Phoenix\n" << "11. EXIT" << endl;
          cin >> choice;
          if(choice = 11)
            {
              cout << "Program terminated." << endl;
              break;
            }

          trip.setDistance(choice);
          cout << "The distance from Chicago to " << trip.getDestination() << " is "
               << trip.getDistance() << endl;

          trip.setRate();
          cout << "The speed you will be travelling at from Chicago to "
               << trip.getDestination() << " is " << trip.getRate() << endl;

          trip.calculateTime();
          cout << "The time it will take to travel from Chicago to "
               << trip.getDestination() << " at " << trip.getRate()
               << " miles per hour will be:\n " << trip.getTime() << " hours."
               << endl;
        }
    }
问题出在输出上。即使if语句有一个条件且if选项不是11,该函数仍会打印终止的程序。。我如何解决这个问题,以便如果choice=11,程序终止,如果choice不是11,它将继续并反复循环各种函数,直到choice被选择为11?

您希望choice==11。单个=符号导致将11分配给choice,该分配的计算结果为true

if(choice = 11)
意味着您将选项的值指定为11,并测试该值是否为非零,即是否为真。应该是

if(choice == 11)
您需要使用==进行相等性比较;=是赋值,返回赋值,非零被解释为真

我见过一个试图阻止这个问题的惯例,就是把常数放在左边。以下代码块将产生编译器错误:

      if(11 = choice)
        {
          cout << "Program terminated." << endl;
          break;
        }
正确的格式是

if(choice == 11) {
--- }
=用于赋值,==用于检查相等性


此外,您还必须在do语句末尾给出一个whilecondition,以检查再次进入循环的条件。

如果choice=13{……}

表达式为true ever,赋值表达式值为var的值,上面是choice,赋值表达式为13,13为true


编写编译器可以保护13错误,但是我建议你选择选择==13种方法,因为这种方式会很好理解。< /P>这不是有效的C++代码,缺少重要的位。而且,在编译时打开警告必须始终有匹配。为了得到您想要的帮助,您需要小心,您的代码中除了您所询问的以外,没有其他错误。