gpt4 book ai didi

c++ - 从一串数字 C++ 创建一个数字序列

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:10:39 25 4
gpt4 key购买 nike

我需要制作一个程序,让用户输入一串数字。
然后它输出分组的数字,以便在将数字放在一起时每个分组都比最后一个大。
如果剩余数字的总和小于前一组,则它们将被忽略。
例如:
314159265 会输出 3 14 15 92
此处:3 < 14 <15 < 92 但省略了 65,因为它小于 92

或者
9876543210 会输出 9 87 654 3210
此处:9 < 87 < 654 < 3210

它必须对长度为 1-20 个字符的字符串执行 5 次。

我的代码适用于较短的字符串,即上面的字符串,但是当它们超过 12 个字符时,最终输出就会困惑。

例如:98765432101234567898 输出 9 87 654 3211 12333 而不是 9 81 654 3210 12345 67898这里:9 < 87 < 654 < 3211 < 12333 它应该输出 9 < 87 < 654 < 3210 < 12345 < 67898

我不知道为什么它不适用于较大的字符串,我们将不胜感激任何帮助。

#include<iostream>
#include<iomanip>
#include<math.h>
#include<string>
#include<stdlib.h>

using namespace std;

void input (string &a,string num[20]){
string numfinal,temp;
cout<<"Enter the string of numbers: ";
getline(cin, a);
int length=a.length();
for(int i=0;i<length;i++){
num[i]=a.substr(i,1);
}

for(int r=0;r<length;r++){
int n=atoi(temp.c_str());
int o=atoi(num[r].c_str());
int p=temp.length();
if((length-r<=p)&&(o<n)){
}
else if((o>n)||(r==0)){
temp=num[r];
numfinal=numfinal+temp+" ";
}
else if((o<n)||(o=n)){
int w=n;
temp=num[r]+num[r+1];
n=atoi(temp.c_str());
if(n<w){
int a=1;
int q=r+2;
while(n<w){
temp=temp+num[q];
n=atoi(temp.c_str());
p++;
a++;
}
numfinal=numfinal+temp+" ";
r=r+a;
}
else{
numfinal=numfinal+temp+" ";
r++;
}
}
}
cout<<numfinal<<endl;
}

int main(){
string a;
string num[20];
for(int r=0;r<5;r++){
input(a,num);
}
return 0;
}

最佳答案

此代码有效。但不要忘记编写简单的代码并使用 C++ 编程的新风格。

#include <vector>
using namespace std;
vector<string> Input( )
{
string a;
cin >> a;
vector<string> num;
string current("-1");
string str;
for(auto c : a)
{
str.append(1, c);
if (stoi(str) > stoi(current) )
{
num.push_back(str);
current = str;
cout << str << " ";
str = "";
}
}
cout << endl;
return num;
}

int main() {
for (int i = 0; i<5; i++) {
vector<string> num;
num = Input();
}
return 0;
}

关于c++ - 从一串数字 C++ 创建一个数字序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42124177/

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