PAT题库第一题:格式化输入

题目链接:
https://pintia.cn/problem-sets/994805342720868352/problems/994805528788582400

题目代码:

编程语言一定使用C++,C也可以,不嫌麻烦的话。

// Cprimer.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include 
#include 
#include 
using namespace std;

/**
  this function accept an integer operator,and output in standard output
  Parameter:
   String result: 
        string format of Number that needed to be formated in standardized style
   bool isFraction:
         since fraction part and integral part of number has a little difference in some situations
**/
void partition(string result,bool isFraction) {
	
	int len = result.length();
	if (len < 4) {
		cout << result;
	}
	else {


		if (len % 3 == 0) {
			//ordinary cycle
			int i;
			for (i = 0; i < (len / 3) - 1; i++) {
				cout << result.substr(3 * i, 3) << ",";
			}
			//last cycle,it's the last three digit,so you needn't to add comma
			cout << result.substr(3 * i, 3);

		}
		else {
			if (!isFraction) {
				int i = 0;
				//in this case,Needn't deal with special condition,len/3 cycles has extra tail in result string
				cout << result.substr(0, len % 3);
				for (i = 0; i < (len / 3); i++) {
					cout << "," << result.substr(3 * i + len % 3, 3);
				}//integer end
			}
			else {
				int i = 0;
				//in this case,Needn't deal with special condition,len/3 cycles has extra tail in result string
				
				for (i = 0; i < (len / 3); i++) {
					cout << result.substr(3 * i , 3) << ",";
				}//fraction end
				cout << result.substr(result.length() - (len % 3) + 1 - 1, len % 3);
			}

         }
	}//end else condition:less than 4
	
}


int main()
{
	double a, b;
	cin >>a>>b;
    
	//Range Check
	if ((a <= pow(10, 6) && a >= -pow(10, 6))
		&& (b <= pow(10, 6) && b >= -pow(10, 6))) {
		double c = a + b;
		if (c < 0) {
			cout << "-";
			c = 0 - c;
		}
	    int intPart = (int)c;
		//cout << intPart;  //deal with integer part
		partition(to_string(intPart),false);
		double fraction = c - intPart;
		//return directly if it's simple integer operation
		if (fraction == 0) {
			return 0;
		}
	    //cout <<"[" <= 0; i--) {
			if (sFrac[i] != '0') {
				point = i;
				break;
			}
		}
		sFrac = sFrac.substr(0, point + 1);
		//cout << "[" << sFrac << "]" << endl;  //debug truncate result
		partition(sFrac,true);
		return 0;
		
	}
	else {
		//not expected to run,but gracefully exit if it've happened
		cout << "error";
		cout << a<

你可能感兴趣的:(PAT,PAT刷题)