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

C++程序输出问号而非幼犬编号问题排查求助

问题排查与修复方案

我来帮你梳理下程序出问题的原因,主要有两个核心错误导致了输出异常:

1. 错误地将整数编号直接存入字符串

你用 puppies += i; 把幼犬的整数编号 i 追加到字符串变量里,但在C++中,这样做会把整数 i 的数值当作ASCII码值对应的字符来存储,而不是我们想要的数字字符形式。比如当 i=1 时,ASCII码1对应的是不可打印的控制字符,输出时自然就显示成问号或者乱码了。

更合理的做法是:不要用字符串存储多个编号(容易出现拆分问题,比如多位数编号拼接后无法区分),改用 vector<int> 来存储所有远离主人的幼犬编号。这样不仅能准确保存每个编号,后续输出也更方便。

2. 输出逻辑依赖错误的存储方式,导致格式混乱

因为 puppies 字符串里存的是不可见的控制字符,所以输出时看不到正确的幼犬编号,才会出现类似 "Puppy and Puppy too far away" 这种异常内容——中间的编号字符无法正常显示。

修复后的完整代码

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

int main() {
    vector<int> far_puppies; // 存储远离主人的幼犬编号
    int a, b;
    cin >> a >> b;
    int n;
    cin >> n;
    
    for (int i = 1; i <= n; ++i) {
        int x, y;
        cin >> x >> y;
        int dist = abs(a - x) + abs(b - y);
        if (dist > 10) {
            far_puppies.push_back(i); // 将符合条件的编号加入容器
        }
    }
    
    int count = far_puppies.size();
    if (count == 1) {
        cout << "Puppy " << far_puppies[0] << " too far away" << endl;
        cout << "Total " << count << " puppy too far away";
    } else if (count > 1) {
        // 处理多个幼犬的输出格式,最后一个用and连接
        for (int j = 0; j < count - 1; ++j) {
            cout << "Puppy " << far_puppies[j];
            // 只有倒数第二个元素后才加and,前面的用逗号分隔(更符合英文表达习惯)
            if (j == count - 2) {
                cout << " and ";
            } else {
                cout << ", ";
            }
        }
        cout << "Puppy " << far_puppies.back() << " too far away" << endl;
        cout << "Total " << count << " puppies too far away";
    } else {
        cout << "No puppies too far away";
    }
    
    return 0;
}

测试示例输入的输出结果

当输入你提供的示例数据时:

2 1
4
15 15
14 -2
1 3
0 4

程序会输出:

Puppy 1 and Puppy 2 too far away
Total 2 puppies too far away

完全符合你的预期需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 03:54:42