使此函数正确循环

getting this function to loop properly

本文关键字:循环 函数      更新时间:2023-10-16

我正在制作一个函数,给出从芝加哥到某个城市所需的旅行时间。我试图让它循环,这样当用户选择城市时,它会给出所需的时间,然后循环回来问主要问题,让用户选择另一个城市。我还包括一个选项,他们可以在其中退出循环。到目前为止,我所拥有的是:

    main()
    {
      TripInfo trip;
      int choice;
      do
        {
          cout << "You are in Chicago. Where would you like to drive?n"
               << "Enter number of cityn" << "1. New York Cityn" << "2. Bostonn"
               << "3. Philadelphian" << "4. Toronton" << "5. Washington D.C.n"
               << "6. Miamin" << "7. Indianapolisn" << "8. Los Angelesn"
               << "9. San Fransiscon" << "10. Phoenixn" << "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语句有一个条件,如果choice不是11,函数仍然会打印"Program terminated"。我该如何解决这个问题,如果choice=11,程序会终止,如果choose不是11,它会继续并一次又一次地循环各种函数,直到choice被选择为11?

您需要choice == 11。一个=符号会将11分配给选择(并且该分配结果为true)。

您需要使用==来比较是否相等;=是赋值,返回赋值,非零值被解释为true。

我看到的一个试图防止这个问题的惯例是将常量放在左边。以下代码块将产生编译器错误:

      if(11 = choice)
        {
          cout << "Program terminated." << endl;
          break;
        }
if(choice = 11)

意味着您为choice指定一个值11,并测试该值是否为非零,这是真的。应该是

if(choice == 11)

正确的格式是

if(choice == 11) {
--- }

=用于分配,==用于检查相等性。

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

if(choice=13){…}

表达式始终为true,赋值表达式值为var的值,以上为select,赋值表达式为13,13为true。

您可以编写13=choice来保护编译器的错误,但我建议您编写choice==13的方法,因为这种方法会很好地理解。