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

如何将C++中int argc、char* argv的值保存到int变量?预设参数100无法存入int limit

问题分析与解决方案

你的代码核心问题是错误地将参数个数argc赋值给了limit,而没有从argv数组中读取实际传入的参数值。argc表示命令行参数的总数(第一个参数永远是程序自身的路径/名称),你需要的数值参数是存储在argv[1]中的字符串,必须转换成int类型后才能赋值给limit。

修正后的代码

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

int main(int argc, char* argv[]) {
    // 检查是否传入了足够的参数
    if (argc < 2) {
        cerr << "请传入一个整数参数作为上限值" << endl;
        return 1;
    }

    int limit;
    // 使用C++风格的stoi转换,支持异常捕获
    try {
        limit = stoi(argv[1]);
    } catch (const invalid_argument& e) {
        cerr << "传入的参数不是有效的整数" << endl;
        return 1;
    } catch (const out_of_range& e) {
        cerr << "传入的整数超出int类型范围" << endl;
        return 1;
    }

    cout << "上限值为:" << limit << endl;

    for (int candidate = 2; candidate < limit; candidate++) {
        int total = 1;
        // 修改判断条件为<=,避免漏掉平方根为整数的因数
        for (int factor = 2; factor * factor <= candidate; factor++) {
            if (candidate % factor == 0) {
                total += factor;
                // 避免重复累加相同因数(如4的因数2)
                if (factor != candidate / factor) {
                    total += candidate / factor;
                }
            }
        }
        if (total == candidate) {
            cout << candidate << ' ';
        }
    }
    return 0;
}

关键改动说明

  • 参数读取逻辑:从argv[1]读取用户传入的字符串参数,通过stoi转换为int类型。相比C风格的atoi,stoi能捕获无效输入(非数字字符串、超范围数值)的异常,提升程序健壮性。
  • 合法性检查:增加argc < 2的判断,确保用户传入必要参数;通过try-catch处理转换异常,避免程序崩溃。
  • 因数求和优化:原代码factor * factor < candidate会漏掉平方根为整数的情况(如4的因数2),改成<=并增加重复因数判断,保证求和准确。

使用方式

编译程序后,在命令行中传入参数运行,例如:

./your_program 100

此时limit会被赋值为100,程序将输出2到99之间的完全数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 07:40:30