zoukankan      html  css  js  c++  java
  • C/C++对一个整数求出每一位的数值

    题目描述

     Write a program that reads an integer with 3 digits and adds all the digits in the integer.For example,if an integer is 932,the sum of all its digits is 9+3+2=14.

    输入格式

     An integer x.(100<=x<=999)

    输出格式

     The sum of all x's digits

    样例输入
    932
    样例输出
    14
    
    提示

     Use the % operator(求余) to extract digits, and use the / operator(取整除法) to remove the extracted digit. For instance,932 % 10 = 2 and 932 / 10 = 93.


    代码:

    #include <iostream> 
    using namespace std;
    
    
    int main()
    {
    	int a,b,c,d;
    	cin>>a;
    	b = a % 10; 
    	//cout<<b<<endl;
    	int temp1 = a / 10;
    	c = temp1 % 10;
    	//cout<<c<<endl;
    	int temp2 = temp1 / 10;
    	d = temp2 % 10;
    	//cout<<d<<endl;
    	cout<<b+c+d<<endl;
    	return 0;
    }

    解题关键是“%” 和 “/”两个操作,利用“/”可以将一个百位数逐一去掉最后的一位,然后再用“%”操作算出最后一位的数值。
  • 相关阅读:
    pip安装
    nfs
    源码方式安装软件
    自启动
    multipath
    linux永久添加和删除路由
    iscsi
    linux识别workstation磁盘的uuid
    centos镜像各种cd,dvd版本区别
    转:C# 中 MSCHART 饼状图显示百分比
  • 原文地址:https://www.cnblogs.com/lvlang/p/10586514.html
Copyright © 2011-2022 走看看