题目:
# 口算练习题
## 题目描述
王老师正在教简单算术运算。细心的王老师收集了i道学生经常做错的口算题,并且想整理编写成一份练习。 编排这些题目是一件繁琐的事情,为此他想用计算机程序来提高工作效率。王老师希望尽量减少输入的工作量,比如 $\texttt{5+8}$ 的算式最好只要输入 $\texttt 5$ 和 $\texttt 8$,输出的结果要尽量详细以方便后期排版的使用,比如对于上述输入进行处理后输出 $\texttt{5+8=13}$ 以及该算式的总长度 $6$。王老师把这个光荣的任务交给你,请你帮他编程实现以上功能。
## 输入格式
第一行为数值 $i$
接着的 $i$ 行为需要输入的算式,每行可能有三个数据或两个数据。
若该行为三个数据则第一个数据表示运算类型,$\texttt a$ 表示加法运算,$\texttt b$ 表示减法运算,$\texttt c$ 表示乘法运算,接着的两个数据表示参加运算的运算数。
若该行为两个数据,则表示本题的运算类型与上一题的运算类型相同,而这两个数据为运算数。
## 输出格式
输出 $2\times i$ 行。对于每个输入的算式,输出完整的运算式及结果,第二行输出该运算式的总长度
## 样例 #1
### 样例输入 #1
```
4
a 64 46
275 125
c 11 99
b 46 64
```
### 样例输出 #1
```
64+46=110
9
275+125=400
11
11*99=1089
10
46-64=-18
9
```
## 提示
数据规模与约定
对于 $50\%$ 的数据,输入的算式都有三个数据,第一个算式一定有三个数据。
对于所有数据,$0<i\leq 50$,运算数为非负整数且小于 $10000$。
代码:
#include<stdio.h>
#include<string.h>
int n;//输入次数
char a,ch;//a表示输入的第一个字符 ch表示运算符
int number1, number2, result;
int main() {
scanf_s("%d", &n);
//n次
while (n--) {
scanf_s("%c", &a,1);
number1 = 0, number2 = 0;
if (isdigit(a)) {//如果是数字 (这个函数要记得) 把它转换为数字类型
number1 = number1 + a - '0';//加到数字上 (从0开始)
a = getchar();//从输入缓冲区里面读取一个字符 当程序调用 getchar 时,程序就等着用户按键。用户输入的字符被存放在键盘缓冲区中,直到用户按回车为止(回车字符 \n 也放在缓冲区中),当用户键入回车之后,getchar() 函数才开始从输入缓冲区中每次读取一个字符,getchar 函数的返回值是用户输入的字符的 ASCII 码
while (a != ' ') {//当没有遇到空格那肯定是两位数三位数 后面的也就得都是数字
number1 = number1 * 10 + a - '0';
a = getchar();//继续读入下一个
}
//遇到空格之后 开始输入下一个数字
scanf_s("%d", &number2);
}
//若不是数字 还是字符 就按照规则
else {
ch = a;
scanf_s("%d %d", &number1, &number2);
}
printf("%c", ch);
if (ch == 'a') {//加法
result = number1 + number2;
printf("%d+%d=%d\n", number1, number2, result);
}
if (ch == 'c') {//乘法
result = number1 * number2;
printf("%d*%d=%d\n", number1, number2, result);
}
if (ch == 'b') {
result = number1 - number2;
printf("%d-%d=%d\n", number1, number2, result);
}
//下面是输出整个式子长度 有点像统计几位数那样
int len = 0;
//数1计算长度
if (number1 == 0) {//0也算长度
len++;
}
else {
while (number1) {
number1 /= 10;
len++;
}
}
//数2计算长度
if (number2 == 0) {//0也算长度
len++;
}
else {
while (number2) {
number2 /= 10;
len++;
}
}
//结果计算长度 要注意负号会多一个
if (result < 0) {
len++;
result = -result;
}
//转为正的 再和上面的一样
if (result == 0) {//0也算长度
len++;
}
else {
while (result) {
result /= 10;
len++;
}
}
len = len + 2;//还要加2
printf("%d", len);
}
return 0;
}
参考:
#include<bits/stdc++.h>usingnamespacestd;
int n;
char c,ch;
int a,b,q;
intmain(){
cin>>n;
while(n--){
cin>>c;
a=0,b=0;
if(isdigit(c)){
a+=c-'0';
c=getchar();
while(c!=' '){
a=a*10+c-'0';
c=getchar();
}
cin>>b;
}
else {ch=c,cin>>a>>b;}
if(ch=='a')cout<<a<<"+"<<b<<"="<<a+b<<endl,q=a+b;
if(ch=='b')cout<<a<<"-"<<b<<"="<<a-b<<endl,q=a-b;
if(ch=='c')cout<<a<<"*"<<b<<"="<<a*b<<endl,q=a*b;
int len=0;
if(a==0)len++;
elsewhile(a)a/=10,len++;
if(b==0)len++;
elsewhile(b)b/=10,len++;
if(q<0)len++,q=-q;
if(q==0)len++;
elsewhile(q)q/=10,len++;
cout<<len+2<<endl;
}
return0;
}