小学生算术-java&c-统计俩个整数相加时发生多少次进位

问题描述:计算俩个整数在相加时需要多少次进位,处理多组数据,直到输入俩个0.

1.java

import java.util.Scanner;
/**
 * 统计两个数字在相加的时候需要多少次进位,结束标志 输入俩个零
 * @author NEU-2015
 *
 */
public class Demo {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int a = 0;
        int b = 0;
        int count = 0;   //统计多少次进位
        int result = 0;   //a+b 每一位数的结果
        while (input.hasNext()) {
            a = input.nextInt();
            b = input.nextInt();
            count = 0;
            result = 0;
            if(a == 0 && b == 0) {    //结束标志
                input.close();
                break;
            }
            
            while(a > 0 && b > 0) {
                result = (a%10 + b%10 + result) > 9 ? 1 : 0;
                count += result;
                a /= 10;
                b /= 10;
            }
            System.out.println(count);    //输出共进位多少次
        }
    }
}

 

 

 

2.c

#include<iostream>
#include<stdio.h>
using namespace std;
//输入的整数都不超过9个数字
//@author NEU-2015
int main() {
    int a, b;
    while(scanf("%d%d", &a, &b) == 2) {
        if(!a && !b) return 0;
        int c = 0, ans = 0;
        for(int i = 9; i >= 0; i--) {
            c = (a%10 + b%10 + c) > 9 ? 1 : 0;
            ans += c;
            a /= 10;
            b /= 10;
        }
        printf("%d\n", ans);
    }
    return 0;
}

 



 

posted on 2017-09-09 10:02  NEU-2015  阅读(530)  评论(0编辑  收藏  举报

导航