1.#define定义语句和代码块
#include <stdio.h>
#include <stdlib.h>
#define ADD(a,b) ((a)+(b))
int main()
{
int x = 2, y = 3;
printf("%d", ADD(x,y));
return 0;
}
2.自增运算符
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 2, y = 3;
printf("%d", (x++)+1);
return 0;
}
答案:3
3.进制转换
#include <stdio.h>
#include <stdlib.h>
int main()
{
int y = 0, product = 1; //y是10进制结果,product是p^(n-1)
int x, p; //x是p进制数
scanf("%d%d", &x, &p);
while(x != 0){
y = y + (x % 10) * product;
x = x / 10;
product = product * p;
}
printf("%d", y);
return 0;
}
4.计算日期间隔
#include <stdio.h>
#include <stdlib.h>
int month[13][2] = {//平年和闰年的每个月的天数
{0,0},{31,31},{28,29},{31,31},{30,30},{31,31},{30,30},
{31,31},{31,31},{30,30},{31,31},{30,30},{31,31}
};
int isLeap(int year){
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
int main()
{
int time1, y1, m1, d1;
int time2, y2, m2, d2;
while(scanf("%d%d",&time1, &time2) != EOF){
if(time1 > time2){
int temp = time1;
time1 = time2;
time2 = temp;
}
y1 = time1 / 10000, m1 = time1 % 10000 / 100, d1 = time1 % 100;
y2 = time2 / 10000, m2 = time2 % 10000 / 100, d2 = time2 % 100;
int ans = 1; //记录结果
while(y1 < y2 || m1 < m2 || d1 < d2){
d1++;
if(d1 == month[m1][isLeap(y1)] + 1){
m1++;
d1 = 1;
}
if(m1 == 13){
y1++;
m1 = 1;
}
ans++;
}
printf("%d\n", ans);
}
return 0;
}
5.将十进制数y转换为Q进制数z
#include <stdio.h>
#include <stdlib.h>
int main(){
//将十进制数y转换为Q进制数z
int z[40], num = 0;
int y,Q;
scanf("%d %d", &y , &Q);
do{//除积取余法
z[num++] = y % Q;
y = y / Q;
}while( y != 0); //商为零算法终止
int i;
for(i = num-1; i >= 0; i--){
printf("%d", z[i]);
}
return 0;
}
6.判断是否是回文数
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const int maxn = 256; //一行字符串不能超过255
int judge(char str[]){
int len = strlen(str);
int i;
for(i = 0; i < len / 2; i++){
if(str[i] != str[len - 1 - i]){
return 0;
}
}
return 1; //是“回文串”
}
int main(){
char str[maxn];
while(gets(str)){
int flag = judge(str);
if(flag == 1){
printf("YES\n");
}else{
printf("NO\n");
}
}
return 0;
}
7.说反话
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char str[90];
gets(str);
int len = strlen(str), r = 0, h = 0;
char ans[90][90];
int i;
for(i = 0; i < len; i++ ){
if(str[i] != ' '){
ans[r][h++] = str[i];
}
else{
ans[r][h] = '\0';
r++;
h = 0;
}
}
for(i = r; i >= 0; i--){
printf("%s", ans[i]);
if(i > 0)printf(" ");
}
return 0;
}