繁体   English   中英

没有从 c++ 程序中得到任何 output

[英]Not getting any output from c++ program

#include <vector>
#include <cmath>


void print(std::vector <int> const& a) {
    for (int i = 0; i < a.size(); i++) {
        std::cout << a.at(i) << " ";
    }
}

std::vector<int> factors(int n) {
    std::vector<int> vec = {};
    for (int i = 0; i < round(sqrt(n)); i++) {
        if (size(factors(i)) == 0) {
            vec.push_back(i);
        }
        std::cout << i;
    }
    return vec;
}

int main() {
    std::vector<int> vec = factors(600851475143);
    print(vec);
    }

这是我的Project Euler #3的 C++ 代码。

C++ 的新手,所以我的代码在语法上可能完全错误,但是我没有收到任何构建错误(使用 Visual Studio)。

但是没有得到任何 output。 我知道这可能是我的错,程序可能运行得非常慢。 但我在 python 中使用相同的迭代方法对此进行了编程,并且它在快速运行时完美运行。

编辑:

但是,我在控制台中收到此消息:

D:\RANDOM PROGRAMMING STUFF\PROJECTEULER\c++\projecteuler3\x64\Debug\projecteuler3.exe (process 13552) exited with code 0.
Press any key to close this window . . .

如果启用编译器警告,您应该会看到溢出警告

prog.cc: 在 function 'int main()': prog.cc:23:36: warning: overflow in conversion from 'long int' to 'int' changes value from '600851475143' to '-443946297' [-Woverflow] 23 | std::vector vec = 因素(600851475143);

所以传递给factors的不是600851475143而是-443946297

当然Gaurav已经给出了正确的答案。 这是修复它的方法,从 int 更改为 unsigned long long,以允许在没有任何外部库的情况下支持的最大整数

#include <cmath>
#include <iostream>
#include <vector>



void print(std::vector<int> const& list){
    for( auto const& item : list){
        std::cout << item << "\n";
    }
}

std::vector<int> factors(unsigned long long n) {
    std::vector<int> vec = {};
    for( int i = 0; i < std::round(std::sqrt(n)); ++i ){
        if( factors(i).empty() ) {
            vec.push_back(i);
        }
        //std::cout << i << ", ";
    }
    return vec;
}

int main() {
    std::vector<int> vec = factors(600851475143ULL);
    print(vec);
}

我还做了一些其他的小改动:

  • 将 print 的 foor 循环更改为基于范围的 for 循环
  • 添加了分隔符 i 打印
  • 向函数添加了 std:: 命名空间
  • 将 size(vec) == 0 替换为空以提高可读性

另一个好习惯是使用-Wall编译以启用更多警告和-Werror以便您实际上被迫处理所有警告而不是将它们刷掉。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM