找回密碼 或 安全提問
 註冊
|註冊|登錄

伊莉討論區

搜索
尊貴會員無限下載附件你準備好成為出色的版主了嗎?安全提問(回答) 和 永久尊貴會員 事宜
催眠上原亞衣偷拍出包王女ntrgekkbox
scop838back to abp 859astrallu閃亂神樂対魔忍desert s

休閒聊天興趣交流學術文化旅遊交流飲食交流家庭事務PC GAMETV GAME
熱門線上其他線上感情感性寵物交流家族門派動漫交流貼圖分享BL/GL
音樂世界影視娛樂女性頻道潮流資訊BT下載區GB下載區下載分享短片
電腦資訊數碼產品手機交流交易廣場網站事務長篇小說體育運動時事經濟
上班一族博彩娛樂

(4月新番)[繁]無職轉

(4月新番)[繁]怪異與

[繁]轉生貴族憑鑑定技

[繁]怪物轉生 Re:Mons

(4月新番)[繁]神明渴

[繁]怪異與少女與神隱
C & C++ 語言C# 語言Visual Basic 語言PHP 語言JAVA 語言
查看: 1177|回復: 1
打印上一主題下一主題

[作業]C++求解 可計算次方的計算機[複製鏈接]

Rank: 2Rank: 2

帖子
380
積分
319 點
潛水值
11552 米
跳轉到指定樓層
樓主
發表於 2012-10-9 07:36 PM|只看該作者|倒序瀏覽
如果瀏覽伊莉時速度太慢或無法連接,可以使用其他分流瀏覽伊莉,www01.eyny.com(02,03)。
希望做出一計算機除了+-*/ 再加入^ 計算次方
例如 2+3*2^3 會正確地算出26
(次方優先判斷後*/再+-)

以下是上課練習+課本求解才弄出的基本四則運算計算機
可是要加上次方就GG了
  1. #include <iostream>                  
  2. #include <cstdlib>                    
  3. #include <cctype>                     
  4. #include <cstring>z
  5. using std::cin;
  6. using std::cout;
  7. using std::endl;

  8. void eatspaces(char* str);            // Function to eliminate blanks
  9. double expr(char* str);               // Function evaluating an expression
  10. double term(char* str, int& index);   // Function analyzing a term
  11. double number(char* str, int& index); // Function to recognize a number
  12. char* extract(char* str, int& index); // Function to extract a substring
  13. const int MAX(80);                    // Maximum expression length,
  14.                                       // including '\0'
  15. int main()
  16. {
  17.    char buffer[MAX]={0};    // Input area for expression to be evaluated

  18.    cout<<"我是計算機唷 出題目吧~"<<endl<<endl;

  19.    for(;;)
  20.    {
  21.       cin.getline(buffer, sizeof buffer);   // Read an input line
  22.       eatspaces(buffer);                    // Remove blanks from input

  23.       if(!buffer[0])                        // Empty line ends calculator
  24.          return 0;

  25.       cout << "\t= " << expr(buffer)        // Output value of expression
  26.            << endl << endl;
  27.    }
  28. }


  29. // Function to eliminate spaces from a string
  30. void eatspaces(char* str)
  31. {
  32.    int i(0);                              // 'Copy to' index to string
  33.    int j(0);                              // 'Copy from' index to string

  34.    while((*(str+i)=*(str+j++))!='\0')  // Loop while character
  35.                                                // copied is not \0
  36.       if(*(str+i) != ' ')                    // Increment i as long as
  37.          i++;                                  // character is not a space
  38.    return;
  39. }

  40. // Function to evaluate an arithmetic expression
  41. double expr(char* str)
  42. {
  43.   double value(0.0);                   // Store result here
  44.   int index(0);                        // Keeps track of current character position

  45.   value = term(str, index);            // Get first term

  46.   for(;;)                              // Indefinite loop, all exits inside
  47.   {
  48.     switch(*(str + index++))           // Choose action based on current character
  49.     {
  50.       case '\0':                       // We're at the end of the string
  51.          return value;                 // so return what we have got

  52.       case '+':                        // + found so add in the
  53.          value += term(str, index);    // next term
  54.          break;

  55.       case '-':                        // - found so subtract
  56.          value -= term(str, index);    // the next term
  57.          break;

  58.       default:                        
  59.          cout<<"發生錯誤~!!!"<<endl;
  60.          exit(1);
  61.     }
  62.   }
  63. }

  64. // Function to get the value of a term
  65. double term(char* str, int& index)
  66. {
  67.   double value(0.0);                   // Somewhere to accumulate
  68.                                        // the result

  69.   value=number(str, index);          // Get the first number in the term

  70.   // Loop as long as we have a good operator
  71.   while(true)
  72.   {

  73.     if(*(str+index) == '*')          // If it's multiply,
  74.       value *= number(str, ++index);   // multiply by next number

  75.     else if(*(str+index) == '/')     // If it's divide,
  76.       value /= number(str, ++index);   // divide by next number
  77.     else
  78.       break;
  79.   }
  80.   return value;                        // We've finished, so return what
  81.                                        // we've got
  82. }

  83. // Function to recognize a number in a string
  84. double number(char* str, int& index)
  85. {
  86.   double value(0.0);                   // Store the resulting value
  87.   
  88.   if((*(str + index) == '(') || (*(str + index) == '{'))            // Start of parentheses
  89.   {
  90.     char* psubstr=NULL;            // Pointer for substring
  91.     psubstr = extract(str, ++index);   // Extract substring in brackets
  92.     value = expr(psubstr);             // Get the value of the substring
  93.     delete[]psubstr;                   // Clean up the free store
  94.     return value;                      // Return substring value
  95.   }

  96.   // There must be at least one digit...
  97.   if(!isdigit(*(str + index)))
  98.   { // There's no digits so input is junk...
  99.     cout<<"發生錯誤~!!!"<<endl;
  100.     exit(1);
  101.   }

  102.   while(isdigit(*(str + index)))       // Loop accumulating leading digits
  103.     value = 10*value + (*(str + index++) - '0');

  104.                                        // Not a digit when we get to here
  105.   if(*(str+index) != '.')            // so check for decimal point
  106.     return value;                      // and if not, return value

  107.   double factor(1.0);                  // Factor for decimal places
  108.   while(isdigit(*(str + (++index))))   // Loop as long as we have digits
  109.   {
  110.     factor *= 0.1;                     // Decrease factor by factor of 10
  111.     value = value + (*(str + index) - '0')*factor;   // Add decimal place
  112.   }

  113.   return value;                        // On loop exit we are done
  114. }

  115. // Function to extract a substring between parentheses
  116. // (requires cstring)
  117. char* extract(char* str, int& index)
  118. {
  119.   char buffer[MAX];                   // Temporary space for substring
  120.   char* pstr=NULL;
  121.   int numB(0);                // Pointer to new string for return
  122.   int numL(0);                        // Count of left parentheses found
  123.   int bufindex(index);                // Save starting value for index

  124.   do
  125.   {
  126.     buffer[index - bufindex] = *(str + index);
  127.     switch(buffer[index - bufindex])
  128.     {
  129.       case '}' :
  130.         if(0==numB)   
  131.         {
  132.            buffer[index - bufindex] = '\0';  // Replace ')' with '\0'
  133.           ++index;
  134.           pstr = new char[index - bufindex];
  135.           if(!pstr)
  136.           {
  137.             cout<<"阿阿阿 程式崩壞----!!!"<<endl;
  138.             exit(1);
  139.           }
  140.           strcpy(pstr,buffer); // Copy substring to new memory
  141.           return pstr;           
  142.          }   
  143.          else
  144.           numB--;                      // Reduce count of '(' to be matched
  145.           break;  
  146.            
  147.       case '{' :
  148.            numB++;     
  149.            break;

  150.       case ')':
  151.         if(0 == numL)
  152.         {
  153.           buffer[index - bufindex] = '\0';  // Replace ')' with '\0'
  154.           ++index;
  155.           pstr = new char[index - bufindex];
  156.           if(!pstr)
  157.           {
  158.             cout<<"阿阿阿 程式崩壞----!!!"<<endl;
  159.             exit(1);
  160.           }
  161.           strcpy(pstr,buffer); // Copy substring to new memory
  162.           return pstr;                 // Return substring in new memory
  163.         }
  164.         else
  165.           numL--;                      // Reduce count of '(' to be matched
  166.           break;

  167.       case '(':
  168.         numL++;                        // Increase count of '(' to be
  169.                                    // matched
  170.         break;
  171.       }
  172.   } while(*(str + index++) != '\0'); // Loop - don't overrun end of string

  173.   cout<<endl<<"=3="<<endl;
  174.   exit(1);
  175. }
複製代碼


...
瀏覽完整內容,請先 註冊登入會員
分享分享0收藏收藏0支持支持0
回覆中加入附件並不會使你增加積分,請使用主題方式發佈附件。

使用道具檢舉

dueseven 該用戶已被刪除
頭香
發表於 2012-10-10 12:40 PM|只看該作者
本帖最後由 dueseven 於 2012-10-10 12:42 PM 編輯

建議你先將中序表示式先轉換成後(or前)序式後,再來做四則運算。
如此一來,你也可以定義你自己的運算子並且定義自訂運算子的優先順序。

使用道具檢舉

您需要登錄後才可以回帖 登錄 | 註冊

Powered by Discuz!

© Comsenz Inc.

重要聲明:本討論區是以即時上載留言的方式運作,對所有留言的真實性、完整性及立場等,不負任何法律責任。而一切留言之言論只代表留言者個人意見,並非本網站之立場,用戶不應信賴內容,並應自行判斷內容之真實性。於有關情形下,用戶應尋求專業意見(如涉及醫療、法律或投資等問題)。 由於本討論區受到「即時上載留言」運作方式所規限,故不能完全監察所有留言,若讀者發現有留言出現問題,請聯絡我們。有權刪除任何留言及拒絕任何人士上載留言,同時亦有不刪除留言的權利。切勿上傳和撰寫 侵犯版權(未經授權)、粗言穢語、誹謗、渲染色情暴力或人身攻擊的言論,敬請自律。本網站保留一切法律權利。
回頂部