编程序,用getchar函数读入两个字符给c1和c2,然后分别用putchar 函数和printf
函数输出这两个字符。思考以下问题:
(1)变量c1和c2应定义为字符型还是整型?或二者皆可?
(2)要求输出c1和c2值的ASCII码,应如何处理?用putchar函数还是printf函数?
(3)整型变量与字符变量是否在任何情况下都可以互相代替?如:
char c1,c2;
与
int c1,c2;
是否无条件地等价?
1. #include <stdio.h> int main( ) { int c1,c2; //整型定义 printf(“请输入两个整数c1,c2:"); scanf("%d,%d",&c1,&c2); printf("按字符输出结果:\n"); printf(“%c,%c\n",c1,c2); printf("按ASCII码输出结果为:\n"); printf("%d,%d\n",c1,c2); return 0; } 2. #include <stdio.h> int main( ) { char c1,c2;//定义字符型变量 int i1,i2;//定义整型变量 printf("请输入两个字符c1,c2:"); scanf("%c,%c",&c1,&c2); i1=c1; i2=c2; printf(“按字符输出结果:\n"); printf("%c,%c\n",i1,i2); printf("按整数输出结果:\n"); printf("%d,%d\n",c1,c2); return 0; } 3.1 #include <stdio.h> int main( ) { char c1,c2; //定义为字符型 int i1,i2; //定义为整形 printf(“请输入两个整数i1,i2:"); scanf(“%d,%d”,&i1,&i2); c1=i1; //将整数复制给字符变量 c2=i2; printf("按字符输出结果:\n"); printf(“%c,%c\n",c1,c2); printf(“按整数输出结果:\n"); printf(“%d,%d\n",c1,c2); return 0; } 3.2 #include <stdio.h> int main( ) { char c1,c2; printf(“请输入两个字符c1,c2:"); c1=getchar( ); c2=getchar( ); printf(“用putchar语句输出结果为:"); putchar(c1); putchar(c2); printf("\n"); printf("用printf语句输出结果为:"); printf(“%c,%c\n",c1,c2); return 0; }
1.
#include <stdio.h>
int main( )
{
int c1,c2; //整型定义
printf(“请输入两个整数c1,c2:");
scanf("%d,%d",&c1,&c2);
printf("按字符输出结果:\n");
printf(“%c,%c\n",c1,c2);
printf("按ASCII码输出结果为:\n");
printf("%d,%d\n",c1,c2);
return 0;
2.
char c1,c2;//定义字符型变量
int i1,i2;//定义整型变量
printf("请输入两个字符c1,c2:");
scanf("%c,%c",&c1,&c2);
i1=c1;
i2=c2;
printf(“按字符输出结果:\n");
printf("%c,%c\n",i1,i2);
printf("按整数输出结果:\n");
3.1
char c1,c2; //定义为字符型
int i1,i2; //定义为整形
printf(“请输入两个整数i1,i2:");
scanf(“%d,%d”,&i1,&i2);
c1=i1; //将整数复制给字符变量
c2=i2;
printf("按字符输出结果:\n");
printf(“按整数输出结果:\n");
printf(“%d,%d\n",c1,c2);
3.2
printf(“请输入两个字符c1,c2:");
c1=getchar( );
c2=getchar( );
printf(“用putchar语句输出结果为:");
putchar(c1);
putchar(c2);
printf("\n");
printf("用printf语句输出结果为:");
}
这道题你会答吗?花几分钟告诉大家答案吧!
扫描二维码,关注牛客网
下载牛客APP,随时随地刷题