输入输出样例
输入
4
a 64 46
275 125
c 11 99
b 46 64
输出
64+46=110
9
275+125=400
11
11*99=1089
10
46-64=-18
9
这题让我发现了sscanf和sprintf的强大之处,下面再回顾一下
- sscanf()函数:从字符串中读取指定格式的数据
sscanf(str,"%d",&num1);
//从字符串str中读取整型数据存入num1中
- sprintf()函数:将格式化的数据写入字符串
sprintf(arr, "%d-%d=%d", num1, num2, ans);
//将字符串写入arr中
原本尝试使用atoi()和itoa()函数来进行字符串和数字之间的转换,结果判题的机器无法识别
- atoi()——把字符串转换成整型数
num=atoi(str);
- itoa()——把一整数转换为字符串
itoa(num, str, 10);
参考代码
#include <stdio.h>
#include <cctype>
#include <stdlib.h>
#include <string.h>
#include <bits/stdc++.h>
int main()
{
int T;
scanf("%d", &T);
while (T--)
{
int num1, num2;
int ans=0;
char str[10];
char arr[100];
char ex;
scanf("%s", str);
if (isalpha(str[0]))
{
if (str[0] == 'a')
{
ex = 'a';
scanf("%d%d", &num1, &num2);
ans = num1 + num2;
sprintf(arr, "%d+%d=%d", num1, num2, ans);
printf("%s", arr);
printf("\n%d\n", strlen(arr));
memset(arr, 0, sizeof(arr));
}
if (str[0] == 'c')
{
ex = 'c';
scanf("%d%d", &num1, &num2);
ans = num1 * num2;
sprintf(arr, "%d*%d=%d", num1, num2, ans);
printf("%s", arr);
printf("\n%d\n", strlen(arr));
memset(arr, 0, sizeof(arr));
}
if (str[0] == 'b')
{
ex = 'b';
scanf("%d%d", &num1, &num2);
ans = num1 - num2;
sprintf(arr, "%d-%d=%d", num1, num2, ans);
printf("%s", arr);
printf("\n%d\n", strlen(arr));
memset(arr, 0, sizeof(arr));
}
}
else
{
// num1 = atoi(str);
sscanf(str,"%d",&num1);
scanf("%d", &num2);
if (ex == 'a')
{
ans = num1 + num2;
sprintf(arr, "%d+%d=%d", num1, num2, ans);
printf("%s", arr);
printf("\n%d\n", strlen(arr));
memset(arr, 0, sizeof(arr));
}
if (ex == 'c')
{
ans = num1 * num2;
sprintf(arr, "%d*%d=%d", num1, num2, ans);
printf("%s", arr);
printf("\n%d\n", strlen(arr));
memset(arr, 0, sizeof(arr));
}
if (ex == 'b')
{
ans = num1 - num2;
sprintf(arr, "%d-%d=%d", num1, num2, ans);
printf("%s", arr);
printf("\n%d\n", strlen(arr));
memset(arr, 0, sizeof(arr));
}
}
}
}