Do while循环不起作用吗?

时间:2012-04-15 00:37:50

标签: c++

在我的程序中。我的do-while循环不起作用,我不知道为什么。我想要的do-while循环是为了减轻用户在想要输入另一个号码时重新运行程序的需要。

2 个答案:

答案 0 :(得分: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完全相同。

答案 1 :(得分:-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;
}

我的想法是尝试检查用户可能输入的“RUN aGAiN”的任何变化(无论是大写/小写还是其他......很可能是你的问题所在...)

好的,我稍微清理了你的代码......: - )


编辑:并且,是的:绝对没有理由在runagain循环中重新声明do { } while()

相关问题