当我输入与数组中的数字匹配的电荷数时,为什么我的程序不工作。请参阅功能
#include <iostream>
#include <cmath>
using namespace std;
string returnWord(int arr[], int SZ)
{
int nums = 0;
string answer;
cout << "Please enter a charge number: ";
cin >> nums;
for (int i = 0; i < SZ; i++) {
if (nums == arr[i]) {
answer = "This is Valid";
}
else {
answer = "This is Invalid"; // When I enter the valid number this is what prints out
}
}
return (answer);
}
int main()
{
const int SZ = 18;
int nums[SZ] = { 5658845, 4520125, 7895122, 8777541, 8451277, 1302850,
8080152, 4562555, 5552012, 5050522, 7825877, 1250255,
1005231, 6545231, 3852085, 7576651, 7881200, 4581002 };
string something = returnWord(nums, SZ);
cout << something << " ";
}
我的程序运行时将无法正确打印出";这是有效的";,即使我从数组中输入了正确的数字。我不明白为什么会发生这种事。
只有当数组中的最后一个数字有效时,它才会打印This is Valid
,因为您在整个数组中继续循环,并在每个步骤中分配answer
。
如果检查的值有效,则应尽早从函数返回,或者在循环后返回其无效。
示例:
std::string returnWord(int arr[], size_t SZ) {
cout << "Please enter a charge number: ";
if (int nums; cin >> nums) {
for (size_t i = 0; i < SZ; i++) {
if (nums == arr[i]) {
return "This is Valid"; // return directly when it's found valid
}
}
}
return "This is Invalid"; // the whole array is checked, it was invalid
}
这是用于带有内部if语句的循环
for (int i = 0; i < SZ; i++) {
if (nums == arr[i]) {
answer = "This is Valid";
}
else {
answer = "This is Invalid"; // When I enter the valid number this is what prints out
}
}
逻辑上不正确。当数组的当前元素不等于搜索到的数字时,它可以立即中断。
重写循环,例如以下方式
std::string returnWord( const int arr[], size_t SZ )
{
int nums = 0;
std::cout << "Please enter a charge number: ";
std::cin >> nums;
size_t i = 0;
while ( i != SZ && nums != arr[i] ) ++i;
return i == SZ ? "This is Invalid" : "This is Valid";
}