C/C++程序设计与算法第三周:平年闰年的判定、牛顿法求平方根

记录自己学习慕课课程--程序设计与算法(一)

1.奇数偶数的判定

#include<iostream>
using namespace std;
int main(){
  int number;
  cin>>number;              // 奇数偶数判定
  if(number%2 != 0)
    cout<<"this is odd"<<endl;
  else
    cout<<"this is even"<<endl;
  return 0;
}

2.

输入一个年份判断
  是否建国、建党整十周年
  闰年、平年

#include<iostream>
using namespace std;
int main(){
  int year;
  cin>> year;
  if(year > 1949 &&(year - 1949) % 10 == 0)
     cout<<year <<"是建国"<<(year - 1949) <<"周年"<<endl;
  else if(year > 1921 && (year - 1921) % 10 == 0 )
     cout<<year<<"是建党"<<(year-1921)<<"周年"<<endl;
  else if(year % 4 == 0 && year % 100 != 0 || year %400 == 0)
     cout<<year<<"是闰年"<<endl;
  return 0;
}

3.输入数字1-7对应输出周几

#include<iostream>
using namespace std;
int main(){
   int n;
   cin>>n;
   switch(n){
   case(1):cout<<"星期一";
           break;
   case(2):cout<<"星期二";
           break;
   case(3):cout<<"星期三";
           break;
   case(4):cout<<"星期四";
           break;
   case(5):cout<<"星期五";
           break;
   case(6):
   case(7):cout<<"周末";
           break;
   default:cout<<"error number!";
   }
   cout<<endl;
   return 0;
}

4.例题描述:牛顿法求输入数的平方根
      欲求a的平方根,首先猜测一个值X1 = a/2
      作为其平方根,然后根据迭代公式
      Xn+1 = (Xn + a/Xn) / 2;
      确定Xi ,知道Xi 足够逼近a的平方根

#include<iostream>
using namespace std;
#define EPS  0.0001
int main(){
   double a;
   cin>>a;
   if(a>=0){
     double x,last_x;
     x = a/2;
     while(x*x - a > EPS || a - x*x > EPS){
      last_x = x;
	  x = (last_x + a/last_x)/2;
     }
	 cout<<x<<endl;
   }
   else
     cout<<"error number"<<endl;
   return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值