gpt4 book ai didi

c++ - out_of_bounds:基本字符串C++

转载 作者:行者123 更新时间:2023-12-02 10:17:09 24 4
gpt4 key购买 nike

我必须做一个程序,该程序从命令行获取参数,并使用公式A(i)* x ^(i)来计算N个元素的总和。命令行中的参数按以下顺序排列:x,n,A0 .... An。 polynom()函数有效,但PrettyPrint()函数无效。目的是通过将转换为字符串并放入“,”来放置千位分隔符。在调试程序之后,变量numString的值是我期望的值,但是,当我尝试打印它时,出现以下错误消息:(我也在另一个编译器上尝试了该代码,并得到了相同的结果)

terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::replace: __pos (which is 4294967295) > this->size() (which is 12)

我的密码
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
#include <stdlib.h>

using namespace std;

double polynom(vector<double> list) {
// ToDo: Exercise 2.b - compute value of P(x)
double result = 0;
int i=0;
while(i<=list[1]){
result = result + (list[2+i] * pow(list[0],i));
//cout<<list[i];
i++;
}
return result;
}

void prettyPrint(double decimal)
{
// ToDo: Exercise 2.c - print number with thousands separators to console

int count = 0;
double decimal1 = decimal;
while(decimal1>1){
count++; //find how many digits are before the .
decimal1 = decimal1/10;
}
cout<<count<<endl;
string numString = to_string(decimal);
cout<< numString[count-1]<<endl;
int i = count-1;
while(i>=0){
i -= 2;
numString = numString.insert(i,",");
}

cout<<numString;
//std::cout << decimal;
}

int main(int argc, char* argv[])
{
// ToDo: Exercise 2.a - read parameters and x, deal with invalid values

// ToDo: Exercise 2.b - print P(x)
// ToDo: Exercise 2.c - print P(x) with prettyPrint
vector<double> list;
for ( int i = 1 ; i < argc ; i++){
double tmp (stod(argv[i]));
list.push_back(tmp); // add all arguments to the vector
}

if(list[1] < 1 || list[list.size()-1] == 0){
cout<<"invalid arguments"<<endl; //terminate program if the arguments are not acceptable
exit(1);
}

cout<<polynom(list)<<endl;
prettyPrint(polynom(list));
std::cout << "Hello World";
return 0;
}

最佳答案

这部分

while(i>=0){
i -= 2;
numString = numString.insert(i,",");
}

是错误的,因为您在减去之后和检查之前正在使用 i

添加检查将消除此问题。
while(i>=0){
i -= 2;
if (i > 0) numString = numString.insert(i,",");
}

关于c++ - out_of_bounds:基本字符串C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61563950/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com