C/C++经典程序训练3—模拟计算器
Time Limit: 1000 ms Memory Limit: 8192 KiB
Submit Statistic
Problem Description
简单计算器模拟:输入两个整数和一个运算符,输出运算结果。 Input
第一行输入两个整数,用空格分开; 第二行输入一个运算符(+、-、*、/)。 所有运算均为整数运算,保证除数不包含0。 Output
输出对两个数运算后的结果。 Sample Input
30 50
- Sample Output
1500 Hint
Source
#include<stdio.h>
int main()
{
int a,b;
char s;
scanf("%d%d\n",&a,&b);
scanf("%c",&s);//用两个scanf,避免换行出错
switch(s)
{
case'+':
printf("%d\n",a+b);
break;
case'-':
printf("%d\n",a-b);
break;
case'*':
printf("%d\n",a*b);
break;
case'/':
if(b==0) printf("Divided by zero\n");
else printf("%d\n",a/b);
break;
default:
printf("input error\n");
}
return 0;
}
c中利用scanf()函数输入字符串,在按下回车后’\n’字符是被存储在了缓存区的,如果下一次继续读入字符这个换行符可能会产生影响,也可能不会产生影响。总结如下:
不会产生影响的情况:第二次输入为“字符串”(或数字);
scanf("%s",a); scanf("%s",b); printf("%s\n",a); printf("%s\n",b);
如果输入为:
hello world
则输出也为:
hello world
scanf()函数更基于获取单词(get world)而不是获取字符串(get
string);scanf()是以第一个非空白字符开始读入的,故第一次读入字符所输入的’\n’,在第二个scanf()函数开始时被忽略掉了。(“%d”同理)会产生影响的情况:第二次读入的是‘字符’:
scanf("%c",&a); scanf("%c",&b); printf("%c\n",a); printf("%c\n",b);
如果输入h,在按下回车后会直接输出:
h
则直接就会输出为h和两个空行:
h
因为读入的是字符,所以在第一个字符读完后的’\n’,
在运行第二个scanf()时直接被读取了,所以第二个printf()函数输出为两个’\n’;如果想消除’\n’的影响可以在中间加个getchar()函数;
--------------------- 作者:1xuan 来源:CSDN 原文:https://blog.csdn.net/sinat_40043477/article/details/77748944
版权声明:本文为博主原创文章,转载请附上博文链接!