即使我一直输入数字,我的代码也不会输出多行。为什么我的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;
}
答案 0 :(得分:0)
您需要移动
cin >> input;
进入while循环和break语句仅应在输入q或Q的情况下执行。另外,您还需要在下一个循环之前将输入重置为某些内容。在下面的示例中,我将其空白。
#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;
}