2017-08-24 37 views
-3

我的問題是我怎麼能檢查是否以數字開頭5本科學生數量和那些後畢業生開始與9檢查數量與某些數字

的條件爲:開始本科生初始註冊費爲R500,研究生初始註冊費爲R600。本科模塊的費用爲每個模塊R1100,研究生模塊的費用爲每個模塊R2000。

我已經設置了我的類和我的主要看起來如下,但我不知道我應該在主或在我的實現文件中檢查條件?

//Application 
    #include "Student.h" 
    #include "PostGradStudent.h" 
    #include <iostream> 

    using namespace std; 

    int main() 
    { 
     double regFee, modFee, addFee; 

     PostGradStudent thePostGradStudent(1, 2, 3,12, "Rohan", 2, "Hole-In-One avenue", "BSc", "Thesis"); 
     thePostGradStudent.displayInfo(); 

     return 0; 
    } 

下面是我做了計算,但這裏是我不明白我怎麼能發送正確的價值觀,以主?在這方面 Output

援助將非常感激:

double PostGradStudent::calcFee() //calculate the total fees(registration fee + module fees + any additional fee) for a student 
    { 
     return regFee + modFee + addFee; 
    } 

    void PostGradStudent::displayInfo() 
    { 
     cout.setf(ios::showpoint); 
     cout.setf(ios::fixed); 
     cout << "Details for the student" << endl 
      << "Student Number: " << get_studentNumber() << endl 
      << "Student Name: " << get_studentName() << endl 
      << "Number of Modules: " << get_noModules() << endl 
      << "Address: " << get_address() << endl 
      << "Degree: " << get_degree() << endl 
      << "Total cost of fees: R" << setprecision(2) << calcFee() << endl 
      << "Dissertation: " << get_dissertation() << endl; 

}

當我運行下面的應用程序,我已連接的屏幕截圖。

謝謝 羅漢

+1

轉數轉換成字符串檢查的第一個字符? 'std :: to_string(123).at(0)=='9'// false'。 – BoBTFish

+0

@Bathsheba在哪裏應該檢查主要? –

+0

@RohanvanAswegen:您將我的轉換應用於'get_studentNumber()' – Bathsheba

回答

0

如果n是你的號碼,是一個完整的類型,然後

while (n < -9 || n > 9) n /= 10;

轉變n到第一個數字。如果您不支持signedn,請刪除n < -9 ||部分。

這也有整潔的屬性0是不變的。

做這個數字將比轉換爲std::string更快,但如果你基本上使用字符串(在我看來,至少一個學號不是你想要進行算術運算的東西),然後使用substr & c。

0

有一個數字,你可以使用std::to_string函數將其轉換爲字符串。如果您使用的編譯器不支持C++ 11,請嘗試查看itoa函數。

轉換完成後,使用[]運算符檢查指定的stringchar[]項就足夠了。

由於@ muXXmit2X也表示std::ostringstream可以用於轉換。 實際的解決方案選擇取決於您的要求的細節。

實現範例:

// check if the 'value' has digit '2' set in the hundreds pos 
// assumption: there are at least 3 digits 
uint32_t value = 21245; 
char check = '2'; 

// substr 
std::string text = std::to_string(value); 
bool isTrue1 = text.substr(text.size()-3, 1) == std::string(1, check); // true 
bool isTrue2 = text[text.size()-3] == check; // true 

// itoa 
char buffer[10]; 
itoa(value, buffer, 10); 
bool isTrue3 = buffer[strlen(buffer)-3] == check; // true 

// numerical 
bool isTrue4 = (value/100 % 10) == 2; // true 
+0

_如果你沒有使用不支持C++ 11的編譯器,請嘗試查看itoa函數或使用'std :: ostringstream'。 – muXXmit2X