2012-04-15 151 views
-3

在我的程序中。我的do-while循環不工作,我不知道爲什麼。我希望do-while循環做的是減輕用戶在他想輸入另一個數字時重新運行該程序的需要。雖然循環不工作?

+4

怎麼回事?它不是在編譯?這是不是在做你期望的? – 2012-04-15 00:40:40

+1

既然是作業,我會給你幾個提示。不要在循環中聲明第二個runagain字符串。你在上面聲明的那個沒問題。在輸入'再次運行'後,嘗試打印出字符串包含的內容。你會注意到cin停在空白處。而是看看getline。 – 2012-04-15 00:41:24

+1

如果用戶進入「再次運行」會怎樣​​? – 2012-04-15 00:41:27

回答

-1

試試這個:

#include<iostream> 
#include<string> 

double tester; 
using namespace std; 

void stoupper (std::string& s) 
{ 
    std::string::iterator i = s.begin(); 
    std::string::iterator end = s.end(); 

    while (i != end) { 
      *i = std::toupper((unsigned char)*i); 
      ++i; 
    } 
} 

double squarerootfinder (double number, double divisor){ 
    tester = (number/(divisor * divisor)); 

    if (divisor == 1) { 
      return 1; 
    } 
    else { 
      if (tester != (int)tester) divisor = squarerootfinder(number, divisor - 1); 
    } 

    return divisor; 
} 

int main() { 
    string runagain; 
    double number, divisor, squareroot, insidepart; 

    do {  
      cout << "Enter a whole number to find the square root of it \n"; 
      cin >> number; 

      divisor = number; 
      squareroot = squarerootfinder(number, divisor); 
      insidepart = number/(squareroot * squareroot); 

      if (insidepart != 1) { 
       cout << squareroot << (char)251 << insidepart; 
       cout << endl; 
      } 
      else { 
       cout << squareroot << endl;     
      } 

      cout << "written by Arpan Gupta! \n"; 
      cout << "Enter run again to run the program again. \n"; 
      cin >> runagain; 

      stoupper(runagain); 

    } while (runagain == "RUN AGAIN");  

    return 0; 
} 

的想法是嘗試和檢查,用戶可以輸入(的「再次運行」的任何變化,無論它是否是所有大/小寫或無論什麼......最有可能這就是你的問題所在......)

好的,我清理了你的代碼有點...... :-)


編輯:而且,是的:絕對沒有理由在你的do { } while()循環內重新申報runagain

1

你在你的主循環是不必要的聲明string runagain;兩次。另外double tester應在squarerootfinder函數中聲明,因爲您不在程序中的任何其他地方使用它。

cin忽略空格你應該看看getline函數來代替。這link提供了一個如何使用它的例子。使用cin這裏是問題的根源。您可以通過簡單地添加該行來測試:

cout<<runagain; 

直接在cin>>runagain;之後。

在此代碼:

cout << "Enter a whole number to find the square root of it \n"; 
cin >> number; 
divisor = number; 
squareroot = squarerootfinder(number, divisor); 

您可以設置divisor=number;然後調用squarerootfinder,但使用的除數,爲什麼不只是做這樣的:

cout << "Enter a whole number to find the square root of it \n"; 
cin >> number; 
squareroot = squarerootfinder(number, number); 

因爲divisornumber相等畢竟。