已知条件循环(C++)

语句格式

1.while (表达式)
{
语句序列
}

2.do
{
语句序列
}while (表达式)

例:求e值

编写程序,使用下列级数近似计算e值,直到最后
一个通项<10-7为止。

e=1+1/1!+1/2!+…+1/n!+…
ui=1/ i!=1 / (i-1)!/ i=ui-1/i

求e的程序1

#include <iostream>
using namespace std;
int main()
{ 
double e=1.0,u=1.0;
int n = 1;
while(u >= 1.0E-7)
{
 u = u/n;
 e = e+u;
 n = n+1;
}
cout << "e = " << e <<"(n = " << n << ")" << endl;
return 0;
}

求e的程序2

#include <iostream>
using namespace std;
int main()
{
 double e=1.0,u =1.0;
 int n=1;
 do
 {
 u = u/n;
 e = e+u;
 n = n+1;
 }while(u>=1.0E-7);
 cout << "e=" << e <<"( n = " << n <<")"<< endl;
 return 0;
}

例:计算实数n次方根

编写程序,能够根据输入的实数x和n,计算x的n次方根
具体要求:

  • 输入0 0时,程序结束
  • 当(x<0且n<=0)或(x<=0且1/n不为整数)时,显示“输入错误”并允许用户继续输入
  • 否则计算并显示x的n次方并允许用户继续输入

计算实数n次方根的程序

#include<iostream>
#include<cmath>
using namespace std;
int main()
{
  double x,n;
  while(1)
  {
  cin>>x>>n;  
  if(x==0&&n==0)
  {cout<<"Program terminated"<<endl;    break}
  else
   if((x<0&&n<=0)||(x<0&&1/n!=int(1/n)))
   {cout<<"error reinput"<<endl;    continue;}
cout<<x<<"\t"<<n<<"th root"<<pow(x,1.0/n)<<endl;
}
return 0;}

注意:

  1. break能够跳出所在位置最近的一层循环
  2. continue能够跳出后续语句,开始新一轮的循环

本例学到

1.While语句
while(1)
{…}
2.break语句
3.continue语句
4.分支语句
if((x<0&&n<=0||(x<0&&1/n!=int(1/n)))
5.pow函数
pow(x,1.0/n)

 

猜你喜欢

转载自blog.csdn.net/Yangye_1018/article/details/106548114