如何将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
相关产品推荐
相关产品推荐

