gpt4 book ai didi

c++ - 为什么我的数组总是给出正确的答案?

转载 作者:行者123 更新时间:2023-12-01 14:48:39 26 4
gpt4 key购买 nike

我的代码在这里说所有值都是真的,即使它们不在数组中。我究竟做错了什么?例如,我可以输入 Chicago,它会说“City found”。我试图改变周围的顺序并将“if(foundIt)更改为if(foundIt = true)。它仍然会做同样的事情。

// MichiganCities.cpp - This program prints a message for invalid cities in Michigan.  
// Input: Interactive
// Output: Error message or nothing

#include <iostream>
#include <string>
using namespace std;

int main()
{
// Declare variables
string inCity; // name of city to look up in array
const int NUM_CITIES = 10;
// Initialized array of cities
string citiesInMichigan[] = {"Acme", "Albion", "Detroit", "Watervliet", "Coloma", "Saginaw", "Richland", "Glenn", "Midland", "Brooklyn"};
bool foundIt = false; // Flag variable
int x; // Loop control variable

// Get user input
cout << "Enter name of city: ";
cin >> inCity;

// Write your loop here
for(int i = 0; i < NUM_CITIES; i++){
if (x = i)
foundIt = true;
}


// Write your test statement here to see if there is
// a match. Set the flag to true if city is found.
if (foundIt)
cout << "City found." << endl;
else cout << "Not a city in Michigan." << endl;





// Test to see if city was not found to determine if
// "Not a city in Michigan" message should be printed.


return 0;

} // End of main()

最佳答案

这个循环

  for(int i = 0; i < NUM_CITIES; i++){
if (x = i)
foundIt = true;
}

没有意义。在控制变量 i 的 if 语句中使用了赋值给变量 x。
if (x = i)

看来你的意思至少
  for(int i = 0; !foundIt && i < NUM_CITIES; i++){
if ( inCity == citiesInMichigan[i] )
foundIt = true;
}

如果你需要找到城市的索引,那么循环看起来像
size_t i = 0;

while ( i < NUM_CITIES && inCity != citiesInMichigan[i] ) i++;

if ( i != NUM_CITIES )
{
// the city is found at position i
}
else
{
// the sity is not found
}

关于c++ - 为什么我的数组总是给出正确的答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60442826/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com