C++一道编程哪错了 编写一个程序,输入一个字符串,从字符串中提取有效的数字,输出它们的总和。
#include <string>
#include <iomanip>
using namespace std;
double function1(int b1, int b2, string s);
double function2(int b1, int b2, string s);
int main()
{
string s;
int len = s.length();
int i, j, b1, b2=0;
double sum;
sum = 0;
getline(cin, s);
for (i = 0; i < len; ++i)
{
if (s[i] >= '0' && s[i] <= '9')
{
b1 = i;
for (j = b1;j < len;++j)
{
int b2 = 0;
if (s[j] >= '0' && s[j] <= '9')
b2 = j;
else break;
}
sum = sum + function1(b1, b2, s);
i = b2;
}
if (s[i] == 46)
{
b1 = i + 1;
for (j = b1;j < len;++j)
{
if (s[j] >= '0' && s[j] <= '9')
{
b2 = j;
}
else break;
}
sum = sum + function2(b1, b2, s);
i = b2;
}
}
cout << endl << "字符串中有效的数字的总和为:" << sum << endl << endl;
system("pause");
return 0;
}
double function1(int b1, int b2, string s)
{
double sum = 0;
for (int i = b1; i <= b2; ++i)
sum = sum * 10 + ((unsigned __int64)s[i] - '0');
return sum;
}
double function2(int b1, int b2, string s)
{
double sum = 0;
for (int i = b1; i <= b2; ++i)
sum = sum / 10 + ((unsigned __int64)s[i] - '0');
return sum / 10;
} 展开
本来想改一改,改着改着改得太多,重写一个供参考——
代码资料:
//#include "stdafx.h"//If the vc++6.0, with this line.
#include <string>
#include <iostream>
#include <iomanip>
using namespace std;
int function1(int &i, string s){
int sum;
for(sum=0;s[i]>='0' && s[i]<='9';i++)
sum = sum * 10 + s[i] - '0';
return sum;
}
int main(int argc,char *argv[]){
string s;
int len,i,sum=0;
cin >> s;
len = s.length();
for(i = 0; i < len; ++i)
if(s[i] >= '0' && s[i] <= '9'){
sum+=function1(i,s);
i--;
}
cout << endl << "字符串中有效的数字的总和为:" << sum << endl << endl;
system("pause");
return 0;
}
要考虑小数情况
那就改一下吧——
代码资料:
//#include "stdafx.h"//If the vc++6.0, with this line.
#include <string>
#include <iostream>
#include <iomanip>
using namespace std;
double function1(int &i, string s){
double sum,k;
for(sum=0.0;s[i]>='0' && s[i]<='9';i++)
sum = sum * 10 + s[i] - '0';
if(s[i]=='.')
for(k=10.0,i++;s[i]>='0' && s[i]<='9';k*=10,i++)
sum+=(s[i]-'0')/k;
return sum;
}
int main(int argc,char *argv[]){
string s;
int len,i;
double sum=0.0;
cin >> s;
len = s.length();
for(i = 0; i < len; ++i)
if(s[i] >= '0' && s[i] <= '9' || s[i]=='.'){
sum+=function1(i,s);
i--;
}
cout << endl << "字符串中有效的数字的总和为:" << sum << endl << endl;
system("pause");
return 0;
}
2019-10-20
#include<cstdlib>
#define BufLen 256
using namespace std;
char buf[BufLen];
int main()
{
const string Digital="0123456789";
string s;
int start=0,end;
long long sum=0;
cin.getline(buf,BufLen);
s.assign(buf);
do
{
start=s.find_first_of(Digital,start);
if(string::npos!=start)
{
end=s.find_first_not_of(Digital,start+1);
if(string::npos==end)
end=s.length();
sum+=atol(s.substr(start,end-start).c_str());
start=end+1;
}
}while(string::npos!=start);
cout<<sum<<endl;
return 0;
}