會寫程式的貓
2008年12月17日
有待改良-題目
User:
MY BLOG
Class:
c++
,
c++ 疑難雜症
我承認我真的在偷懶= =!!
//輸入一字串 三個數字 //會自動運算 + - * / 並有錯誤提示 #include
#include
#include
using namespace std; double toN( string str ){//字串轉換成數字 double ans=0; double n=0; double sn=0; for( int x=0 ; x < str.size() ; x++ ){ if(str[x]>='0' && str[x]<='9'){ sn++; } } for( int x=0 ; x < sn ; x++ ){ if(str[x] >= '0' && str[x] <= '9'){ ans+=((double)str[x]-48)*(pow(10,sn-n-1)); n++; } } return ans; } void error( string str ){//判斷是否是錯誤運算式 int p1=0 , p2=0 , n=0 ; for( int x=0 ; x < str.size() ; x++ ){//判斷 符號位元在哪個點 if( ( str[x] >= 48 && str[x] <= 57 )|| str[x] == '+' || str[x] == '-' || str[x] == '*' || str[x] == '/' ){ if(( str[x] == '+') || (str[x] == '-' ) || (str[x] == '*') || (str[x] == '/' ) ){ if( n%2 == 1 ){ p1=x; n++; if( p1 == p2+1 ){ cout << "Error !" ; exit(0); } }else{ p2=x; n++; if( p2 == p1-1 ){ cout << "Error !" ; exit(0); } } } }else{ cout << "Error !" ; exit(0); } } } int sumN( string str ){//計算有幾個 數字 int n=1 ; for( int x=0 ; x < str.size() ; x++ ){//判斷 符號位元在哪個點 if( ( str[x] == '+' ) || ( str[x] == '-' ) || ( str[x] == '*' ) || ( str[x] == '/' ) ){ n++; } } return n; } void toOP( string *op , int *op_pout , string str ){//儲存所有的 符號 int n=0 ; for( int x=0 ; x < str.size() ; x++ ){ if( ( str[x] == '+' ) || ( str[x] == '-' ) || ( str[x] == '*' ) || (str[x] == '/' ) ){ op[n] = str[x];//儲存 符號 op_pout[n] = x;//判斷 符號位元在哪個點 n++; } } } void toS( string s , string *sn , int *op_pout) {//拆解字串 int n=0; for( int x=0 ; x < s.size() ; x++ ){ if( x == op_pout[n] ){ x++; n++; } sn[n] += s[x]; } } int main(){ string s ;//使用者輸入的 運算式 cout << "運算式 = " ; cin >> s; error( s );//看是否為合法運算式 string sn[ sumN( s ) ];//拆解後的字串 宣告 double n[ sumN( s ) ];//數字陣列 宣告 string op[ sumN( s )-1 ];//符號位元宣告 int op_pout[ sumN( s )-1 ]; //符號位址位元宣告 toOP( op , op_pout , s );//儲存所有的 符號位元 toS( s , sn , op_pout ); for( int x=0 ; x < sizeof(op)/sizeof(op[0]) ; x++ ) cout << op[x] << " = " << op_pout[x] << endl; cout << endl << "--分解字串--" << endl; for( int x=0 ; x < sizeof(sn)/sizeof(sn[0]) ; x++ ) cout << x << " = " << sn[x] << endl; cout << endl << "--數字陣列--" << endl; for( int x=0 ; x < sizeof(n)/sizeof(n[0]) ; x++ ){//儲存成數字陣列 n[x] = toN(sn[x]); cout << x << " = " << n[x] << endl; } //運算式撰寫中... }
沒有留言:
張貼留言
較新的文章
較舊的文章
首頁
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言