-3

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

4

2 回答 2

1

string runagain;您在主循环中声明了两次,这是不必要的。也double tester应该在squarerootfinder函数中声明,因为您不会在程序的其他任何地方使用它。

cin忽略空格,您应该查看 getline 函数。此链接提供了如何使用它的示例。在这里使用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毕竟是平等的。

于 2012-04-15T00:51:38.603 回答
-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()循环中重新声明。

于 2012-04-15T00:49:24.363 回答