闰年测试和对输入的非法判断

1问题描述

输入一个测试用例,判断输入用例是否为闰年

2方法使用

这里用到两个函数方法第一个方法由于都在if语句中判断,所以不好测试,第二个方法可以更加明确的判断

3具体代码

#include<stdio.h>
#include<sstream>
#include<string>

using namespace std;

void judge(int year){
bool b;
 if (year % 4 == 0)
         b=true;
 if (year % 100 == 0)
         b=false;
 if (year % 400 == 0)
           b=true;
 if(b==true)
     cout<<"runnian"<<endl;
 if(b!=true)
      cout<<"no runnian"<<endl;
 
}

void judge2(int a)
{
if((a%4==0&&a%100!=0)||(a%400==0))
   cout<<"run nian "<<endl;
else
   cout<<"no run nian";
}

int main(){
 string t;
 int n;
 stingstream ss;
 while(cin>>t){
    ss<<t;
    ss>>n;
    if(!ss.good()){
        cout<<"error";
        break;
    }
    judge(n);
        judge2(n);

 }
 return 0;
}

其中stringstream可以将任意格式的数据转换,ss.good()可以判断是否转换成功。

原文地址:https://www.cnblogs.com/lichongjie/p/4396591.html