zoukankan      html  css  js  c++  java
  • A+B格式1001

    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并以标准格式输出和——也就是说,数字必须用逗号分隔成三组(除非数字个数少于四位)。

    输入规格:

    每个输入文件包含一个测试用例。每种情况都包含一对整数a和b,-1000000 <= a, b <= 1000000。其中这些数字用空格隔开。

    输出规范:

    对于每个测试用例,您应该在一行中输出a和b的和。总和必须用标准格式写。

    样例输入:

    -1000000 9

    样例输出:

    -999,991

    题解:

    把数字a+b的和转化成字符串,如果第一位是负号先跳过,只要当前位的下标i满足(i + 1) % 3 等于字符串长度 % 3并且i不是最后一位,就在逐位输出的时候在该位输出后的后面加上一个逗号。

    #include <stdio.h>
    int main(){
      int a,b;
      scanf("%d%d",&a,&b);
      a+=b;        //将a,b的和赋值给a
      if(a<0){
        printf("-");    //若和为负数,则输出“-”号
        a=-a;    //将和转化为相反数
      }
      int c[7],n=0,i;
      if(a==0) printf("0");    //若和为0,则输出0
      else{
        while(a>0){
          c[n++]=a%10;
          a/=10;
        }    //将和值的每一位数字从低位到高位依次存入数组
        for(i=n-1;i>=0;i--){
          printf("%d",c[i]);    
          if(i%3==0&&i!=0) printf(",");
        }    //从高位到低位依次输出,并加入标准格式中的“,”号
      }
      printf("
    ");
      return 0;
    }
  • 相关阅读:
    React实现新闻网站--使用动态路由获取不同列表内容
    Bootstrap4 轮播+模态框+提示框+弹出框
    JDK 升级问题小结
    JDK8 指南(译)
    如何学习一门编程语言
    redis 系列5 数据结构之字典(上)
    sql server 临时表(上) Tempdb概述
    redis 系列4 数据结构之链表
    redis 系列3 数据结构之简单动态字符串 SDS
    redis 系列2 知识点概述
  • 原文地址:https://www.cnblogs.com/2228212230qq/p/10887614.html
Copyright © 2011-2022 走看看