You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++程序输入与数组匹配的充值号时无法输出有效结果怎么办

问题根因

逻辑错误出在for循环的判断分支中:
每遍历一个数组元素,就会覆盖一次answer的值。哪怕你前面已经匹配到了正确的充值号,只要后续遍历到不匹配的元素,answer就会被重新赋值为This is Invalid,最终返回的永远是和数组最后一个元素的对比结果。
比如你输入的是数组第一个元素5658845,第一次判断会把answer设为有效,但后续遍历剩下17个不匹配的元素时,会反复把answer覆盖为无效,最终返回的就是无效提示。

另外你的代码未包含<string>头文件就使用了string类型,部分编译器可能因为iostream间接引入该头文件可以运行,但不符合C++标准,存在编译失败风险。

修复方案

调整循环判断逻辑:

  • 先把answer默认值设为无效,只要匹配到对应充值号,就赋值为有效并直接跳出循环,不需要继续遍历后续元素
  • 避免每轮循环都覆盖answer的值

修复后的完整代码如下:

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

string returnWord(int arr[], int SZ)
{
    int input_num = 0;
    // 默认先设置为无效
    string answer = "This is Invalid";
    cout << "Please enter a charge number: ";
    cin >> input_num;
    for (int i = 0; i < SZ; i++) {
        if (input_num == arr[i]) {
            // 匹配到就修改结果,直接跳出循环,不需要继续遍历
            answer = "This is Valid";
            break;
        }
    }
    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 << " ";
    return 0;
}

内容的提问来源于stack exchange,提问作者John Richardson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 09:54:08