2016-03-09 54 views
0

我收到一條錯誤消息,指出「期望的主表達式」;'令牌「,它突出顯示了我的百分比公式。我試圖重新排列我的代碼,但似乎問題不在其中。';'之前的C++期望primary-expression令牌

const int TOTALSUITES = 120; 

for (int floor = 10; floor <= 16; floor++) { 
    if (floor != 13) { 
     do { 
      cout << "Please enter the number of suites occupied on the floor " << floor << ":"; 
      cin >> numOccupied; 

      if ((numOccupied <0) || (numOccupied >20)) { 
       goodChoice = false; 
       cout << "\n\t\t**ERROR" << numOccupied << " ***\n\n"; 
       cout << "*** Choice must be from [0-20]***\n"; 
      } 
      else { 
       goodChoice = true; 
      } 
      totalOccupied += numOccupied; 
     } while (!goodChoice); 
    } 
} 

percentage = (totalOccupied/TOTALSUITES) * 100% ; 
cout << endl; 
cout << "Hotel has " << TOTALSUITES << endl; 
cout << "Number of occupied suites is " << totalOccupied << endl; 
cout << "The percentage of occupied suites is " << percentage << endl; 
system("pause"); 
return 0; 
+0

在哪條線你會得到錯誤? – fabersky

回答

1

100%不是100%。 100%正試圖以不正確的方式使用% operator。要乘以100%,您只需使用1,這是不需要的,因爲1本身就是任何時間。

1
percentage = (totalOccupied/TOTALSUITES) * 100% ; 

這是無效的語法。將其更改爲此。

percentage = (totalOccupied/TOTALSUITES); 

假設你totalOccupied不是浮動,你應該這樣做,以及:

percentage = (static_cast<float>(totalOccupied)/TOTALSUITES); 
+0

我一直在掙扎一段時間T.T謝謝你<3! – sunnysmile24

+0

我寧願看到一個'雙'(並會upvote),但我明白你的觀點。 – Bathsheba

1

%實際上是在C 運營++,需要兩個參數。

100%因此在語法上不是有效的。

假設你想讓%代替「除以100」運算符,最簡單的事情就是從代碼中刪除100%

注意totalOccupied/TOTALSUITES將在整數算術如果totalOccupied進行也是intunsigned。通過將其中一個參數提升爲double來解決這個問題,或者用1.0預乘該術語。

這裏使用
2

%是求餘運算是一個二元運算符... 所以這是你必須做的事情......

percentage = (totalOccupied/TOTALSUITES)* 100; 

//然後,你在這一點上有COUT百分比...做到這一點

cout<<"the percentage of occupied suites is"<<percentage<<"%"; 
+0

我在cout聲明中使用的「%」符號僅用於顯示百分比符號,並且對代碼 –

+0

@ SunnySmile24沒有邏輯影響,如果我的答案或任何其他答案您認爲合適,則標記爲最合適,即標記爲upvote之下的刻度, downvote按鈕......以便其他人知道它的答案已經得到了回答 –

相關問題