【发布时间】:2013-05-04 22:06:46
【问题描述】:
我正在尝试编写一个函数,它将字符串作为参数,搜索其中是否有“p”或“e”,将其拆分为单独的字符串,将“p”替换为"3.14..." 和 "e" 与 "2.71...",将所有字符串转换为双精度,然后将所有转换后的字符串相乘.例如,当参数为“123.45p4e9.2”时,函数将其拆分为“123.45”、“p”、“ 4”、“e”和“9.2”,然后用常量替换字符:“123.45”、“” 3.14...”、“4”、“2.71...”和“9.2”,之后转换所有其中双倍并相乘:123.45*3.14*4*2.71*9.2。
问题是当我给它一个只有数字的字符串时,没有任何'p'或'e'(例如“2.4”或“32 "),它返回 0。但是,当我给它 "e"、"p" 或 "ep" 时,它返回 " 2.71..."、"3.14..." 或 "8.53...",所以在这种情况下它运行良好.当我尝试给它提供数字和字符组合的字符串时,问题又回来了。当我输入“3p”时,函数返回正确的结果:“9.42...”。另一方面,当我输入“p3”时,它返回“3.14...”,尽管它应该仍然是“9.42...”。看起来它根本不适用于数字,如果出现“e”或“p”,它似乎没有发现第一个字符之后的数字。
有人可以查看代码并找出问题所在吗?我已经找了好几个小时了,但从逻辑上讲,一切似乎都很好。
#include "stdafx.h"
#include <iostream>
#include <conio.h>
#include <string>
#include <math.h>
#include <windows.h>
#define NULL "null"
using namespace std;
double stale(string w);
int main(){
//Testing the function
string liczba;
cout << "Type the number: ";
cin >> liczba;
double wynik = stale(liczba);
cout << endl << "Result: " << wynik << endl << endl;
system("PAUSE");
}
double stale(string w){
string *wartosc = new string[w.length()]; //Dynamic string array
for(int i = 0; i < w.length(); i++){ //String array is filled with "null"
wartosc[i] = NULL;
}
{ //Bracket only to control lifespawn of liczba and element_wartosc variables
string liczba = NULL; // There'll be built a number between e and p
int element_wartosc = 0;
for(int i = 0; i < w.length(); i++){ //Searching argument string for e and p
switch(w[i]){
case 'p':
if(liczba != NULL){ //Ends generating number, which isn't e or p
wartosc[element_wartosc] = liczba;
liczba = NULL;
element_wartosc++;
wartosc[element_wartosc] = "3.14159265358979323846";
element_wartosc++;
}else{
wartosc[element_wartosc] = "3.14159265358979323846";
element_wartosc++;
}
break;
case 'e':
if(liczba != NULL){ //Ends generating number, which isn't e or p
wartosc[element_wartosc] = liczba;
liczba = NULL;
element_wartosc++;
wartosc[element_wartosc] = "2.71828182845904523536";
element_wartosc++;
}else{
wartosc[element_wartosc] = "2.71828182845904523536";
element_wartosc++;
}
break;
default:
if (liczba == NULL){
liczba = w[i]; //Starts filling liczba variable with first character
}else if(w[i] == '\0'){
wartosc[element_wartosc] = liczba; //Ends generating number on argument string end
break;
}else{
liczba = liczba + w[i]; //Builds the number
}
}
}
}
double wynik = 0; //There will be the result
for(int i = 0; i < w.length(); i++){
if(wartosc[i] == NULL){ //wartosc array was filled earlier with "null" strings, to distinguish it from entered numbers
continue;
}else{
double liczba = stod(wartosc[i]); //Converting strings onto doubles
if(wynik == 0){
wynik = liczba; //Starting multiplification
}else{
wynik *= liczba; //Multiplification
}
}
}
delete[] wartosc; //Removing dynamic array
return wynik; //The result is returned
}
【问题讨论】:
-
#define NULL "null"看起来不是个好主意。当人们看到NULL时,他们期望的是一个空指针。 -
不需要用循环清除字符串,你应该只用wartosc->empty();
-
你对 (w[i] == '\0') 的测试永远不会是真的。
标签: c++ arrays string type-conversion multiplication