周练2

7-11 正整数A+B

这种水题都做了好久  还是有一个没过

#include <bits/stdc++.h>

using namespace std;




int main()
{

string s;
getline(cin,s);
int fa=1,fb=1;int a=0,b=0;
int i;
//if(s[0]==' ')fa=0;
for( i=0;s[i]!=' ';i++)
{
  //printf("%d\n",s[i]-'0');
    if(i==0&&s[i]=='0')fa=0;
    if(!((s[i]-'0')<=9&&(s[i]-'0')>=0)){fa=0;}
    else a=a*10+s[i]-'0';

}
for(int k=i+1;s[k]!=' '&&s[k]!='\0';k++)
{
     // printf("%d ",s[k]-' ');
     if(k==i+1&&s[k]=='0')fb=0;
    if(!((s[k]-'0')<=9&&(s[k]-'0')>=0)){fb=0;break;}
    else b=b*10+s[k]-'0';
}
if(a>1000||a==0)fa=0;
if(b>1000||b==0)fb=0;


if(fa)printf("%d",a);
else printf("?");
printf(" + ");
if(fb)printf("%d",b);
else printf("?");
printf(" = ");
if(fa&&fb)printf("%d",a+b);
else printf("?");





return 0;
}
View Code

看到一个比较好的方法

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string a;
    getline(cin, a);
    int m = 0, n = 0;//所有字符串的和
    int x = 0, y = 0;//只有数字的和
    int i = 0;
    for (i; i<a.length(); i++)
    {
        if (a[i] == ' ') break;
        m = m * 10 + (a[i] - '0');
        if (a[i] >= '0'&&a[i] <= '9')
        {
            x = x * 10 + (a[i] - '0');
        }
    }
    for (int j = i + 1; j<a.length(); j++)
    {
        //if(a[j]==' ') break; 
        n = n * 10 + (a[j] - '0');
        if (a[j] >= '0'&&a[j] <= '9')
        {
            y = y * 10 + (a[j] - '0');
        }
    }
    if (m <= 1000 && m >= 1 && m == x)
        cout << m;
    else
        cout << "?";
    cout << " + ";
    if (n <= 1000 && n >= 1 && n == y)
        cout << n;
    else
        cout << "?";
    cout << " = ";
    if (n <= 1000 && n >= 1 && m <= 1000 && m >= 1 && m == x&&n == y)
        cout << m + n;
    else
        cout << "?";
    return 0;
}
View Code

猜你喜欢

转载自www.cnblogs.com/bxd123/p/10183176.html