PAT浙大甲级第一题(学习来自bilibili)

由于近期在备战浙江大学计算机的研究生考试,所以准备参加今年9月以及12月的PAT甲级考试,由于本人对于晴神宝典还未学习完全,又加之考试在即,所以以每天学习并编写1-2题PAT来加深自己对于PAT甲级的理解。
今天是6月7日,第一题是本人于6月5日所学习完成的,当然6月7日也完成了第二题,后面则会每天更新1-2题,并每日学习晴神宝典,也与共同考浙大的同学们共勉,希望今年12月份能收到自己的好消息,各位加油!!!
下面我们就来展示第一题:
PAT T1001 (A+B Format)(本题满分-20point)
试题:
Calculate a+b and output the sum in standard format – that is, the digits must be separated into groups of three by commas (unless there are less than four digits).
Input Specification:
Each input file contains one test case. Each case contains a pair of integers a and b where −10​6​≤a,b≤10​6​. The numbers are separated by a space.
Output Specification:
For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.
Sample Input:
-1000000 9
Sample Output:
-999,991
题目意思在这里就不赘述了!
先来展示一下自己初次写的代码:(初次代码拿了19point)
在PAT系统上使用c

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
int main(){
    int a,b;
    int sum;
	int i=0;
	int n;
	int c[7]; //定义7位数组
    scanf("%d %d",&a,&b);
    sum=a+b;	
    //printf("%d\n",sum);
    int sum1=sum;
	while(sum1 !=0){
	    c[i]=abs(sum1%10);
		sum1=sum1/10;
		i++;
	}
	n=i;
	if(sum<0){
	    printf("-");
	}
	 
	for(int i=n-1;i>=0;i--){
		printf("%d",c[i]);
		if(i%3==0 && i!=0){
		   printf(",");
		}
	}
	if(sum<0){
	     
	}
return 0;
}

这里还差1分,有点可惜。
下面展示本人通过学习后,使用c++所改写的代码:

//代码2(20 POINT)
//初始定义
#include<iostream>
#include<vector>
using namespace std;
int main(){
    int a,b;
    cin>>a>>b;
    int sum=a+b;
    //cout<<sum;  //因为cout是以数值输出,因为输出中存在相应的都好,这里不能使用
    //考虑使用字符数组,每三个字符中间加一个逗号,下面开始讨论情况
    //1、如果计算的sum小于3位数
    if(sum==0){
        cout<<sum;
        return 0;
    }
    //2、如果sum的值为负数,则现在前面cout一个负号‘-’,之后将数值取反即可
    if(sum<0){
        cout<<'-';
        sum*=-1;
    }
    //使用采用vector容器存放相应位数的值,注意需要添加头文件
    vector<int>v;
    while(sum!=0){
        v.emplace_back(sum%10);
        //v.push_back(sum%10);
        sum/=10;
    }
    for(int i=v.size()-1;i>=0;i--){
        cout<<v[i];
        if(i%3==0 && i!=0){
            cout<<',';
        }       
    }
    return 0;
}

这里是用到了vector容器,是c++中STL(标准数据模版库)中的一种。
总结:第一题在题目理解上较为简单,本人一开始采用自己的方法,较为简单的实现了拿了19分,方法二主要的要点是会使用c++的cin与cout函数以及对于c++中STL(标准模版库)中vector容器的使用。
在这里希望和大家一起进步,一起努力学习!!!!!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

L C H

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值