(请直接查看最,请直接查看最后一个代码段)
还有两周考pat,好久没写c 代码了,极限刷题一波,看看有没有机会抱佛大腿。
题目
1001 A B Format (20 分)
Calculatea band 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 integersaandbwhere?106≤a,b≤106. The numbers are separated by a space.
Output Specification:
For each test case, you should output the sum ofaandbin one line. The sum must be written in the standard format.
Sample Input:
-1000000 9
结尾无空行
Sample Output:
-999,991
结尾无空行
思路
先算出两数之和作为待处理数,再除以1000取余数,获得的余数压入栈内(这里我觉得麻烦没有定义专门的栈结构,而是直接在普通数组上操作),然后除法商作为一个新的待处理数量。全部入栈后,从栈顶出发依次取出加上,。
注:
- 要注意栈大小,这里限制了a,b小于等于10的6次方,意味着最大结果为2乘以10的6次方,即最多3节,代表栈的数组长度可取3。
- 在给定的输出标准中最后不是逗号。
我的通过代码:
#include <iostream> using namespace std; int main(){ int a,b,s,result[3]={-1,-1,-1}; cin>>a; cin>>b; s=a b; int i=0; if(s<0){ cout << "-"; s=s*(-1); } while(s>=1000){ result[i ]=s00; s/=1000; } result[i]=s; for(int j=i;j>=0;j--){ if(result[j]>=100 || j==i){ cout<<result[j]; } else if(result[j]>10){ cout<<0; cout<<result[j]; } else{ cout<<0; cout<<0; cout<<result[j]; } if(j==0){ break; } cout << ","; } return 0; }
我在做题过程中遇到的问题:
- 忘了处理符号,负数被打印出来,每个数字有负数╮(─▽─)╭
- 没想到每一节都会出现开头的0丢弃(如1001打印成1,1)。
更多:
搜索发现两点:
- 用c中的printf("%0md",p)该方法可以直接确保输出的数字必须为m位,不足的数字自动在高位补充0,因此无需判断需要补充几个0。
- 使用scanf和printf需要#include <stdio.h>库
- 建议不要同时使用两种输入输出方法
- c 中有stack类别,所以你不必考虑每次调用的数组范围和下标。
- #include <stack>
- 定义:stack <elemtype> stackname
- stackname.empty() 如果栈是空的,返回真理
- stackname.push(elem)
- stackname.top() 返回栈顶元素
- stackname.pop() 删除栈顶元素,请注意这里只删除,返回是void,请按之前需要调整top()
- stackname.size() 返回栈中元素数量
修改后通过的代码如下:
#include <stack> #include <stdio.h> using namespace std; int main(){ int a,b,s,p,size0,size; stack <int> result; scanf("%d%d",&a,&b); s=a b; if(s<0){ printf("-"); s=s*(-1); } while(s>=1000){ result.push(s00); s/=1000; } result.push(s); size0=result.size(); while(true){ p=result.top(); size=result.size(); result.pop(); if(p>=100 || size==size0){ printf("%d",p); } else{ printf("d",p); } if(result.empty()) break; printf(","); } return 0; }
遇到的坑:
- pop()返回空。
- 在判断第一节(为了避免在头部加0)时,首先想到的方法是在循环外取栈顶元素赋予变量top,然后在循环中进行判断top()方法获得的值和top是否相等。忽略可能性。不止一次和top一样的元素(例1001001)size判断没问题。