循环帮助 虽然循环无法正常工作



即使我不断输入数字,我的代码也不会输出超过一行。为什么我的while循环会这样做,我该如何修复它?

  • 当我输入r 12.3 45.6然后输入p 12.3 45.6时,它只输出第一个输入
  • 如果我输入除R r P p之外的任何内容,则应该输出Format error并继续循环,除非用户输入停止循环的q
#include <iostream>
using namespace std;
#include <cmath>
#include <iomanip>
int main() {
float x;
float y;
float M;
float th;
char input;
cin >> input; 
while ((input != 'q') && (input != 'Q')) {// starts while loop wile not inputting eirther q or Q
if ((input == 'r') || (input == 'R')) {
cin >> x >> y; //user inputs x and y
M = sqrt(pow(x, 2) + pow(y, 2)); // M 
th =  atan2(y,x) * (180 / M_PI);// theta in degrees
cout << "POL -> REC: REC: X = " << fixed << setprecision(2)  << x << " Y = " << y << " POL: M = " << M << " A = " << th<< endl;
}
if((input == 'p') || (input == 'P')) { //If user inputs p or P excute rest of code below
cin >> M;//user enters M
cin >> th;// User enters theta

x = (M * cos(M_PI / 180 * th)); // X into degrees
y = M * sin(th * M_PI/180);// y into degrees
cout << "REC -> POL: REC: X = " << fixed << setprecision(2)  << x << " Y = " << y << " POL: M = " << M << " A = " << th << endl;
}
if ((input != 'r') && (input != 'R') && (input != 'p') && (input != 'P')) {//if user enters anything besides p P q Q then output format error
cout << "Format Error!" << endl;
}
break; //stops loop
}
return 0;
}

您需要移动

cin >> input;

进入while循环,并且只有在输入q或q时才应执行break语句。此外,在下一次循环之前,您需要将输入重置为某个值。下面的例子我把它留空了。

#include <iostream>
using namespace std;
#include <cmath>
#include <iomanip>
int main() {
float x;
float y;
float M;
float th;
char input;
while (true) 
{
cin >> input;
if ((input == 'r') || (input == 'R')) {
cin >> x >> y; //user inputs x and y
M = sqrt(pow(x, 2) + pow(y, 2)); // M 
th = atan2(y, x) * (180 / M_PI);// theta in degrees
cout << "POL -> REC: REC: X = " << fixed << setprecision(2) << x << " Y = " << y << " POL: M = " << M << " A = " << th << endl;

}
if ((input == 'p') || (input == 'P')) { //If user inputs p or P excute rest of code below

cin >> M;//user enters M
cin >> th;// User enters theta
x = (M * cos(M_PI / 180 * th)); // X into degrees
y = M * sin(th * M_PI / 180);// y into degrees
cout << "REC -> POL: REC: X = " << fixed << setprecision(2) << x << " Y = " << y << " POL: M = " << M << " A = " << th << endl;

}
if ((input != 'r') && (input != 'R') && (input != 'p') && (input != 'P')) {//if user enters anything besides p P q Q then output format error
cout << "Format Error!" << endl;
break;
}
if (input == 'q' || input == 'Q')
break; //stops loop
input = ' ';
}
return 0;
}

相关内容

  • 没有找到相关文章

最新更新