使此函数正确循环
getting this function to loop properly
我正在制作一个函数,给出从芝加哥到某个城市所需的旅行时间。我试图让它循环,这样当用户选择城市时,它会给出所需的时间,然后循环回来问主要问题,让用户选择另一个城市。我还包括一个选项,他们可以在其中退出循环。到目前为止,我所拥有的是:
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的方法,因为这种方法会很好地理解。
相关文章:
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 循环中的随机函数
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 未在函数C++中执行的循环
- 如何在没有可变参数函数的情况下循环函数的参数
- 循环函数中的并行数组
- 如何循环函数,直到新的 mqtt 消息到达
- 循环C++ R 函数
- 为什么我的 while 循环函数只返回"1"?
- Pthread 循环函数永远不会被调用
- 循环函数调用未正确循环!(C++)
- 对于循环函数参数在C++中的奇数
- 具有双重调度的C++多态循环函数
- 循环函数给出"return’ with a value, in function returning void"误差
- 如何用循环函数求和
- 如何使c++中的for each循环函数与自定义类一起工作
- c++分割故障及循环函数
- C++ |需要帮助从 for 循环函数转换 - >递归函数
- 为什么要在 levelDB 的缓存中使用 while 循环(函数 Resize)?
- odeint中的循环函数