c语言练习题29:获得月份天数

获得月份天数

代码:

cpp 复制代码
//法一
#include<stdio.h>
int main() {
	int y = 0;
	int m = 0;
	int days[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
	while (~scanf("%d%*c%d", &y, &m)) {
		int day = days[m];
		if ((y % 4 == 0) && ((y % 400 == 0) || (y % 100 != 0))) {
			if (m == 2) {
				day++;
			}
		}
		printf("%d\n", day);
	}
	return 0;
}
//法二
//#include <stdio.h>
//int main() {
//  int year = 0;
//  int mouth = 0;
//  while (~scanf("%d %d", &year, &mouth)) {
//    if (mouth == 4 || mouth == 6 || mouth == 9 || mouth == 11) {
//      printf("30\n");
//    }
//    else if (mouth == 2) {
//      if (((year % 4 == 0) && ((year % 400 == 0) || (year % 100 != 0)))) {
//        printf("29\n");
//      }
//      else {
//        printf("28\n");
//      }
//    }
//    else {
//      printf("31\n");
//    }
//  }
//  return 0;
//}//法一
#include<stdio.h>
int main() {
	int y = 0;
	int m = 0;
	int days[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
	while (~scanf("%d%*c%d", &y, &m)) {
		int day = days[m];
		if ((y % 4 == 0) && ((y % 400 == 0) || (y % 100 != 0))) {
			if (m == 2) {
				day++;
			}
		}
		printf("%d\n", day);
	}
	return 0;
}
//法二
//#include <stdio.h>
//int main() {
//  int year = 0;
//  int mouth = 0;
//  while (~scanf("%d %d", &year, &mouth)) {
//    if (mouth == 4 || mouth == 6 || mouth == 9 || mouth == 11) {
//      printf("30\n");
//    }
//    else if (mouth == 2) {
//      if (((year % 4 == 0) && ((year % 400 == 0) || (year % 100 != 0)))) {
//        printf("29\n");
//      }
//      else {
//        printf("28\n");
//      }
//    }
//    else {
//      printf("31\n");
//    }
//  }
//  return 0;
//}

知识点:赋值忽略符(%*c

如果⽤⼾输⼊ 2020-01-01 ,就会正确解读出年、⽉、⽇。问题是⽤⼾可能输⼊其他 格式,⽐如 2020/01/01 ,这种情况下, scanf() 解析数据就会失败。 为了避免这种情况, scanf() 提供了⼀个赋值忽略符(assignment suppression character) * 。 只要把 * 加在任何占位符的百分号后⾯,该占位符就不会返回值,解析后将被丢弃。

%*c 就是在占位符的百分号后⾯,加⼊了赋值忽略符 * ,表⽰这个占位符没有对应的 变量,解读后不必返回。

相关推荐
TracyCoder12321 分钟前
LeetCode Hot100(1/100)——1. 两数之和 (Two Sum)
算法·leetcode
进击的小头25 分钟前
常用数字滤波器的特性与适用场景
c语言·算法
APIshop40 分钟前
Java获取item_get-获得某书商品详情接口
java·开发语言·python
狐571 小时前
2026-01-19-LeetCode刷题笔记-1292-元素和小于等于阈值的正方形的最大边长
笔记·算法·leetcode
Henry Zhu1231 小时前
Qt Model/View架构详解(四):高级特性
开发语言·qt·架构
张祥6422889041 小时前
误差理论与测量平差基础笔记六
笔记·算法·概率论
txinyu的博客1 小时前
std::function
服务器·开发语言·c++
多多*1 小时前
图解Redis的分布式锁的历程 从单机到集群
java·开发语言·javascript·vue.js·spring·tomcat·maven
mjhcsp2 小时前
透彻背包DP:从DFS暴力搜索到动态规划的逐步推导
算法·深度优先·动态规划
电商API&Tina2 小时前
Python请求淘宝商品评论API接口全指南||taobao评论API
java·开发语言·数据库·python·json·php