放一下这几天学会的很基础的代码
1.判断三角形
int main()
{
int i = 0;
int j = 0;
int k = 0;
scanf("%d %d %d", &i, &k, &j);
if (i + k > j && i + j > k && j + k > i )
{
if (i == k && k == j)
{
printf("等边三角形\n");
}
else if (i == j || i == k || j == k)
{
printf("等腰三角形\n");
}
else
{
printf("普通三角形\n");
}
}
else
{
printf("非三角形\n");
}
return 0;
}
2.前置后置的使用
int main()
{
int a = 10;
int b = --a;//前置--
//先-a,后使用
a=a-1,b=a
printf("%d %d\n", a, b);
return 0;
}
int main()
{
int a = 10;
int b = a--;//后置--
//先使用,后-a
//b=a,a--
printf("%d %d\n", a, b);
return 0;
}
3.替换
int main()
{
printf("there are %d %c apples\n", 3);
printf("there are three apples\n");
printf("zhangsan will come tonight\n");
printf("%s will come tonight\n", "zhangsan");
printf("a b c d\n");
printf("a b c %c\n", 'd');
printf("Baekgyun says it is 21 o'clock\n");
printf("%s says it is %d o'clock\n", "Bakehyun", 21);
return 0;
}
练习2:使⽤条件表达式实现找两个数中较⼤值
int main()
{
int a = 0;
int b = 0;
scanf("%d %d", &a, &b);
int m = (a > b ? a : b);//三目运算符
printf("%d\n", m);
return 0;
}
练习:3 - 5月为春天
int main()
{
int month = 0;
scanf("%d", &month);
if (month >= 3 && month <= 5)
printf("春天\n");
return 0;
}
练习:⼀年中⽉份是12⽉或者1⽉或者2⽉是冬天
int main()
{
int month = 0;
scanf("%d", &month);
if (month == 1 || month == 12 || month == 2)
printf("冬天\n");
return 0;
}
练习:输⼊任意⼀个整数值,计算除3之后的余数
if 形式
int main()
{
int num = 0;
scanf("%d", &num);
if (num % 3 == 0)
printf("余数为0\n");
else if (num % 3 == 1)
printf("余数为1\n");
else
printf("余数为2\n");
return 0;
}
switch 形式
int main()
{
int num = 0;
scanf("%d", &num);
switch (num % 3)//整形表达式
{
case 0://整形常量表达式
printf("余数是0\n");
break;
case 1:
printf("余数是1\n");
break;
case 2:
printf("余数是3\n");
break;
}
return 0;
}
练习:阅读代码,计算代码输出的结果
#include <stdio.h>
int main()
{
int i = 0, a = 0, b = 2, c = 3, d = 4;
i = a++ && ++b && d++;
a = 1, b = 2, c = 3, d = 4
&& 一假则假,全真则真
int i = 0, a = 1, b = 2, c = 3, d = 4;
i = a++ && ++b && d++;
a = 2, b = 3, c = 3, d = 5
&& 一假则假,全真则真
int i = 0, a = 0, b = 2, c = 3, d = 4;
i = a++||++b||d++;
a = 1, b = 3, c = 3, d = 4
|| 一真则真,全假则假,后面不管
int i = 0, a = 1, b = 2, c = 3, d = 4;
i = a++ || ++b || d++;
a = 2, b = 2, c = 3, d = 4
|| 一真则真,全假则假,后面不管
printf("a = %d\n b = %d\n c = %d\nd = %d\n", a, b, c, d);
return 0;
}
练习:
输⼊⼀个1~7的数字,打印对应的星期⼏
例如:
输⼊:1 输出:星期⼀
输⼊:2 输出:星期⼆
输⼊:3 输出:星期三
输⼊:4 输出:星期四
输⼊:5 输出:星期五
输⼊:6 输出:星期六
输⼊:7 输出:星期天
int main()
{
int day = 0;
scanf("%d", &day);
switch (day)
{
case 1:
printf("星期一\n");
break;
case 2:
printf("星期二\n");
break;
case 3:
printf("星期三\n");
break;
case 4:
printf("星期四\n");
break;
case 5:
printf("星期五\n");
break;
case 6:
printf("星期六\n");
break;
case 7:
printf("星期天\n");
break;
default:
printf("输入错误,请输入1~7的数字");
break;
}
return 0;
}
方法二
int main()
{
int day = 0;
scanf("%d", &day);
switch (day)
{
case 1:
case 2:
case 3:
case 4:
case 5:
printf("工作日\n");
break;
case 6:
case 7:
printf("休息日\n");
break;
default:
printf("输入错误,请输入1~7的数字");
break;
}
return 0;
}