Tor*_*ell 2 c++ loops if-statement while-loop
所以我昨天刚开始 C++,我有相当多的 java 经验,所以这就是原因,我尝试运行这段代码,由于某种原因 while 循环没有循环,我尝试将 if break 语句从 更改ask==false为ask=false,这最终会导致无限循环,甚至不接受用户输入。
这是代码:
#include <iostream>
#include <math.h>
using namespace std;
int main(){
double raduis;
const double pi = 3.14;
bool ask;
while(true){
cout << "Enter the raduis of the circle:"<< endl;
cin >> raduis;
double circ = 2*pi*raduis;
double area = pi*pow(raduis,2);
cout << "The Circumference of the circle is: "<< circ <<endl;
cout << "The Area of the circle is: "<< area<<endl;
cout <<"Would you like to run again?"<< endl;
cin >> ask;
if(ask==false){
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试将 更改bool为char带有"y"or"n"值的值,但没有任何效果。
编辑:好的,我已经解决了问题,按照我输入的 @zdf 的建议,cin >> boolalpha >> ask;它现在工作得很好。
在输入之前调用clear oncin并确保输入仅是0或1,
来自cpreference:
\n\n\n\n
v如果isbool和的类型boolalpha未设置,则如果要存储的值为 \xe2\x80\x8b0\xe2\x80\x8b,false则存储,如果要存储的值为1,true则存储,对于任何其他值std::ios_base::failbit分配给err和true存储。