BJ柯梦


私信TA

用户名:uq_65407390756

访问量:1160

签 名:

等  级
排  名 7606
经  验 1242
参赛次数 0
文章发表 3
年  龄 20
在职情况 学生
学  校
专  业

  自我简介:

TA的其他文章

解题思路:

                   通过获取字符串中的数字和算数符进行判断。

                   详情请看代码。

注意事项:
                   因为字符中数字的ASCII码值是从48开始,所以获取的字符串中数字需要减去'0'或48

参考代码:

#include<stdio.h>

#include<string.h>

int main() {


int correctNum=0;//正确答案的数量

char str[15];//输入的字符串,式子


while (scanf("%s", str) != EOF) {


int len = strlen(str);//获取输入的字符串式子长度

int a, i = 0, b, result;

int index[4];//式子中算数符的下标


//获取算数符所在式子中的下标(式子中有2~3个符号,第一个是+或-,第二个是=,第三个是?)

for (int j = 0; j < len; j++) {

if (str[j] == '+' || str[j] == '-' || str[j] == '=' )

index[i++] = j;

}

//如果等号后面不是?,则进行后续的判断

if (str[index[1] + 1] != '?')

{

/************************获取式子中的第一个数字*******************/

if (index[0] == 3)

a = 100;

else if (index[0] == 2)

a = (str[0]-'0') * 10 + (str[1]-'0');

else if (index[0] == 1)

a = str[0] - '0';


/************************获取式子中的第二个数字*******************/

if (index[1] - index[0] == 4)

b = 100;

else if (index[1] - index[0] == 3)

b =(str[index[0] + 1]-'0') * 10 + str[index[0] + 2]-'0';

else if (index[1] - index[0] == 2)

b = str[index[0] + 1]-'0';



/*************************获取式子中的计算结果********************/

if (len-index[1]==4)

result =(str[index[1] + 1] -'0')* 100 + (str[index[1] + 2] -'0')* 10 + str[index[1]+3]-'0';

else if (len - index[1] == 3)

result = (str[index[1] + 1] -'0')* 10 + str[index[1] + 2]-'0';

else if (len - index[1] == 2)

result = str[index[1] + 1]-'0';


/*****************获取式子中的算数符,并计算出正确的结果***************/

if (str[index[0]] == '+')

{

if (result == a + b)//结果正确则correctNum+1

correctNum++;

}

else if (str[index[0]] == '-')

{

if (result == a - b)

correctNum++;

}

}

}


//输出正确答案的个数

printf("%d", correctNum);

return 0;

}


 

0.0分

3 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答

代码解释器

  评论区