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;
}

解题关键是“%” 和 “/”两个操作,利用“/”可以将一个百位数逐一去掉最后的一位,然后再用“%”操作算出最后一位的数值。

原文链接: https://www.cnblogs.com/lvlang/p/10586514.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C/C++对一个整数求出每一位的数值

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/225081

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 下午12:40
下一篇 2023年2月13日 下午12:41

相关推荐