【string函数使用】PAT A1001 A+B Format (20分)

题目描述

在这里插入图片描述

实现

码前思考

需要使用STL里的string,然后需要将数字转换成字符串,需要用to_string(),这次终于没忘记了,插入逗号要用insert(),还有获取子串substr()

代码实现

#include <iostream>
#include <string>
using namespace std;

int a,b,c;

int main(){
	scanf("%d %d",&a,&b);
	c = a+b;
	string output = to_string(c);
	bool flag=false;
	if(output[0]=='-'){
		output = output.substr(1);
		flag=true;
	}
	//cout<<output<<endl;
	//从末尾开始insert
	for(int i=output.size()-3;i>0;){
		output.insert(i,",");
		i = i-3;
	} 
	output = flag ? "-"+output : output;
	cout<<output<<endl;
	return 0;
}

码后反思

有STL还是舒服啊,之前没用STL,是下面这样的:

#include<stdio.h>
#include<string.h>
#include<math.h>

int main(){
	long long a,b,c;
	scanf("%lld",&a);
	scanf("%lld",&b);
	
	char d[20];
	
	c = a + b;
	if(c<1000 && c> -1000){
		printf("%ld",c);
	}
	else{
		if(c<0){
			printf("-");
		}
		c = fabs(c);
		int num = 0;
		int len = 0;
		char n;
		do{
			if(num != 0 && num%3 == 0)
			{
				d[len] = ',';
				len++;
				num = 0;
			}
			n = c % 10 + '0';
			c = c / 10;
			d[len] = n;
			num++;
			len++;
		}while(c!=0); 
		for(int i = len-1;i>=0;i--){
			printf("%c",d[i]);
		}
	}
	
	return 0;
}

相当于是按位遍历加逗号。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值