没有sqrt()的平方根代码C ++

时间:2017-09-27 07:31:07

标签: c++

我必须创建一个代码,用户输入一个完美正方形的数字,我必须显示它的根。我已经制作了这段代码,但我得到Segmentation Fault 11,在这篇文章中:int j = squareRootVector[i]; squareRoot.push_back(j);。 我无法更改代码,所以有没有办法可以做到这一点?

#include <iostream>
#include <vector>

using namespace std;


int main() {

cout <<

 "Enter the number:\n";

    int input;
    int number = input;
    int divider = 2;
    vector<int> squareRootVector;
    vector<int> squareRoot;

    cin >> number;

    for(int divider = 2; number > 1; divider++) {
        while((number % divider) == 0) {
            number /= divider;
            cout << number << endl;
            squareRootVector.push_back(divider); 
        }
    }


    for(int i = 0; i < squareRootVector.size(); i++) {
        cout << squareRootVector[i] << " ";

        /*******PROBLEM*******/
        if(squareRootVector[i] == squareRootVector[i+1]) {
            int j = squareRootVector[i];
            squareRoot.push_back(j);
        }
        /*********************/
    }

    int root;

    for (int i = 0; squareRoot.size(); i++) {
        root = root * squareRoot[i];
    }

    cout << "Square Root of " << input << " is: " << root << endl;


    return 0;
}

4 个答案:

答案 0 :(得分:3)

使用squareRootVector[i+1]访问i只有size以下for (std::size_t i = 1; i < squareRootVector.size(); i++) { (您的循环构建允许)的行为未定义

考虑写

for

而是相应地重新定义i循环体。我也改变了{{1}}的类型。

答案 1 :(得分:1)

很快,问题是最后一个循环在“for”中:

for(int i = 0; i < squareRootVector.size(); i++)

包含以下内容:

squareRootVector[i] == squareRootVector[i+1];

这是一个“超出限制”的错误:squareRootVector只有squareRootVector.size()个元素(比方说n),元素从0索引到{{ 1}}。

n-1在最后一个循环中指出之后的 squareRootVector[i+1]的最后一个,这是未定义的行为。

答案 2 :(得分:0)

使用vector :: iterator是正确的方法。

for(vector<int>::iterator it = squareRootVector.begin(); it != squareRootVector.end(); ++it)
{
    if( (it+1) == squareRootVector.end() )
    {
        //what to do if there's no next member???
        break;
    }

    if( *it == *(it+1) )
    {
        squareRoot.push_back(*it);
    }
} 

答案 3 :(得分:0)

谢谢你的回答,伙计们。我最终得到了这段代码:

#include <iostream>
#include <vector>

using namespace std;


int main() {

cout << "Enter the number:\n";

int input = 0;
int number = 0;
cin >> input;
number = input;
int divider = 2;
vector<int> squareRootVector;
vector<int> squareRoot;



for(int divider = 2; number > 1; divider++) {
    while((number % divider) == 0) {
        number /= divider;
        squareRootVector.push_back(divider); 
    }
}

int vectorSize = squareRootVector.size() - 1;


for(int i = 0; i < vectorSize; i++) {
    if(squareRootVector[i] == squareRootVector[i+1]) {
        int j = squareRootVector[i];
        squareRoot.push_back(j);
    }
}

int root = 1;

for (int i = 0; i < squareRoot.size(); i++) {
    root = root * squareRoot[i];
}

cout << "Square Root of " << input << " is " << root << endl;


return 0;
}