PAT1001 A+B Format

PAT1001 A+B Format

Knowledge points:

sprintf(s,"%d",c);

Example to understand:

char s[20];
int a=10;
sprintf(s,"%d.jpg",a);
//If a=10, the string s stores "10.jpg".

Problem- solving ideas:
First of all, look at the range of the number of the question, and find that it is not a high-precision question, so you can directly use the integer variable to operate, convert it into a string, and add ',' to the output.

answer:

#include<stdio.h>
#include<math.h>
#include<string.h>
#include<iostream>
using namespace std;

int main()
{
    int a,b;
    cin>>a>>b;
    int c=a+b;
    if(c<0)cout<<'-';
    c=abs(c);
    char s[20];
    sprintf(s,"%d",c);
    int len=strlen(s);
    int m=len/3,n=len%3,start=0;
    if(n==0)
    {
    	cout<<s[0]<<s[1]<<s[2];
    	m--;
    	start=3;
	}
	if(n==1)
	{
		cout<<s[0];
		start=1;
	}
	if(n==2)
	{
		cout<<s[0]<<s[1];
		start=2;
	}
	while(m!=0)
	{
		cout<<',';
		cout<<s[start]<<s[start+1]<<s[start+2];
		start+=3;
		m--;
	}
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326075448&siteId=291194637