zoukankan      html  css  js  c++  java
  • 2017《面向对象程序设计》寒假作业二

    1001. A+B Format (20)解题报告

    github连接:https://github.com/Travaill/object-oriented

    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

    Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.

    Output

    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

    题目大意:计算A+B的值并按标准形式输出,例:100000+1=100,101

    一.我的解题思路

    1.首先看到a+b的范围在-2000000~2000000之间那么第一个让我想到的思路便是,通过除法、取余数取出三位三位来进行输出。

    二.解题过程

    根据这个思路我写出了第一版的代码

    #include<stdio.h>
    #include<math.h>
    int main()
    {
        int a,b,c;
        scanf("%d %d",&a,&b);
        c=a+b;
        if(0<=abs(c)&&abs(c)<1000)
        {
        	printf("%d",c);
    	}
    	if(1000<=abs(c)&&abs(c)<1000000)
    	{
           printf("%d,%03d",(c/1000),abs(c%1000));
    	}
    	if(1000000<=abs(c)&&abs(c)<=20000000)
    	{
    		printf("%d,%03d,%03d",c/1000000,abs(c/1000),abs(c%1000));
    	}
    
    }
    

    提交结果

    对了一半,可见算法本身并无问题,但是有一点瑕疵,经过我的测试,发现当输出1000000上的数的时候会出现问题. !

    第二版

    #include<stdio.h>
    #include<math.h>
    int main()
    {
        int a,b,c;
        int m,n;
        scanf("%d %d",&a,&b);
        c=a+b;
        if(0<=abs(c)&&abs(c)<1000)
        {
        	printf("%d",c);
    	}
    	if(1000<=abs(c)&&abs(c)<1000000)
    	{
           printf("%d,%03d",(c/1000),abs(c%1000));
    	}
    	if(1000000<=abs(c)&&abs(c)<=2000000)
    	{
    		printf("%d,%03d,%03d",c/1000000,abs(c%100000/1000),abs(c%1000));
    	}
    }
    
    

    当数大于100000时,取第二个三位时要先去除前三位的影响.

  • 相关阅读:
    【iOS】获取App的常用文件路径
    【iOS】如何在Objective-C中声明Block?
    实用终端小命令
    iOS开发之NSBundle加载自定义cell需指定其的identifier
    【转】nonatomic, retain,weak,strong用法详解
    iOS控制台打印NSLog增强版
    iOS 内存中的ViewController释放
    iOS ViewController生命周期
    Netty (一) IO 基础篇
    多线程(七) 线程池的实现原理分析
  • 原文地址:https://www.cnblogs.com/linshen/p/6328388.html
Copyright © 2011-2022 走看看