1、输出年月日,当月、日是个位数时前面补0
例如:
20240313
year=2024
month=03
date=13
#include <stdio.h>
int main(void) {
int year = 0;
int month = 0;
int date = 0;
scanf("%4d%2d%2d",&year,&month,&date);
// 输出
printf("year=%d\n",year);
// %02d 0:指的是补0 2:指的是2位
printf("month=%02d\n",month);
printf("date=%02d\n",date);
return 0;
}
2、printf("%d ",sum(a));输出的值: 8 10 12 14 16
#include <stdio.h>
int sum(int a){
// 每次循环进来 c = 0
int c = 0;
// static 修饰 b变量 值是上一次的值
static int b = 3;
c += 1;
b += 2;
return (a+b+c);
}
int main(void) {
int i=0;
int a = 2;
for(i = 0; i < 5; i++){
printf("%d ",sum(a));
}
return 0;
}
3 、优先级:
!运算符=自增自减运算符>算术运算符>关系运算符>&&运算符>||运算符>赋值运算符
int a = 3,b = 4,c = 5;
printf("%d\n",(a||b+c&&b==c)); //1
#include <stdio.h>
int main(void) {
int w = 1,x = 2,y = 3,z = 4;
printf("%d\n",(w<x?w:y)); //1
printf("%d\n",(w<z?y:z)); //3
// 1.先看y<z?y:z
// 2.再w<x?w:y<z?y:z
// w<x?w:(y<z?y:z)
printf("%d\n",(w<x?w:y<z?y:z)); //1
return 0;
}
4、计算n! = 1*2*3*…*n
#include <stdio.h>
// 计算n!
int main(void) {
int i = 1;
int n = 0;
int r = 1;
scanf("%d",&n);
for(i = 1;i <= n;i++){
r *= i;
}
printf("%d",r);
return 0;
}
5、计算1!+2!+…+n!
#include <stdio.h>
// 计算1!+2!+…+n!
int main(void) {
int i = 1;
int sum = 0;
int r = 1;
int n = 0;
scanf("%d",&n);
for(i = 1;i <= n;i++){
r *= i;
sum += r;
}
printf("%d",sum);
return 0;
}
6、在一个有序数组中查找具体的某个数字k
#include <stdio.h>
// 在一个有序数组中查找具体的某个数字n
// 二分查找
int main(void) {
int arr[10]={1,2,3,4,5,6,7,8,9,10};
int k = 7;
int left = 0;
int sz = sizeof(arr)/sizeof(arr[0]);
int right = sz - 1;
while(left<=right){
//int mid = (left+right)/2; 栈可能会溢出
int mid = left + (right - left)/2;
if(arr[mid] < k){
left = mid + 1;
}else if(arr[mid] > k){
right = mid - 1;
}else{
printf("找到数字%d了,下标是%d\n",k,mid);
break;
}
}
if(left > right){
printf("找不到数字%d",k);
}
return 0;
}
7、模拟用户登录情境,并且只能登录三次
#include <stdio.h>
#include <string.h>
// 模拟用户登录情境,并且只能登录三次
int main(void) {
int i=1;
// 假设密码是字符串
char password[20]={0};
char x[]="abcd";
for(i = 0;i < 3;i++){
printf("请输入密码:\n");
scanf("%s",password);
//#include <string.h>
//strcmp():比较2个字符串是否相等,返回值是0,则相等。
if(strcmp(password,x)==0){
printf("密码正确\n");
break;
}else{
printf("密码错误\n");
}
}
if(i==3){
printf("三次密码均错误,退出程序\n");
}
return 0;
}