#include <string>
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
//Make sure there is an argv[1] to check
if (1 < argc) {
std::string option = std::string(argv[1]);
if ("mean" == option) {
float sum = 0;
cout << (argc)<<"\n";
for (int i = 0; i<= argc; i++){
sum = sum+reinterpret_cast<int>(argv[i]);
}
cout<<(sum)<<"\n";
cout<<(argc)<<"\n";
cout<<(sum/argc)<<"\n";
}
return 0
}
我是 C++ 的新手,但这段代码为我输入的内容返回了可笑的值。例如,我使用命令行“homework1 mean 1 2 3 4”,值以千万亿为单位。如果有帮助,我正在使用 64 位机器,我是 c++ 的新手,所以我不确定问题出在哪里。感谢您的帮助。
最佳答案
首先,reinterpret_cast
不会将字符串转换为整数。使用类似 std::stod
的东西。 (取决于你想做多少错误检查。)
二、这些界限
for (int i = 0; i<= argc; i++)
将不起作用,因为 argv[0] 是可执行文件的名称,而 argv[argc] 是一个空指针。使用
for (int i = 2; i < argc; i++){
sum += std::stof(argv[i]);
}
请注意,您的编译器需要支持 c++11 才能正常工作。 (std::stof
等已添加到标准的 c++11 修订版中。)如果没有,您将需要使用 sum += strtof(argv[i], NULL);
。有关详细信息,请参阅 documentation对于 strtof
。
关于c++ - 简单均值计算器的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21650695/