num
. Tính tổng các ký tự số do người dùng nhập vào.
Ví dụ: người dùng nhập num=1234
, kết quả sẽ là 1 + 2 + 3 + 4 = 10
.
r = num % 10
num / 10
sum = sum + r
/* C# Program to Get a Number and Display the Sum of the Digits This is a C# Program to get a number and display the sum of the digits. Problem Description This C# Program Gets a Number and Display the Sum of the Digits. Problem Solution The digit sum of a given integer is the sum of all its digits. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Lession3 { class Program { static void Main(string[] args) { int num, sum = 0, r; Console.WriteLine("Enter a Number : "); num = int.Parse(Console.ReadLine()); while (num != 0) { r = num % 10; num = num / 10; sum = sum + r; } Console.WriteLine("Sum of Digits of the Number : " + sum); Console.ReadLine(); } } }[/su_spolier]
Cùng nhau học tập, khám phá các kiến thức nền tảng về Lập trình web, mobile, database nhé.
Nền tảng kiến thức - Hành trang tới tương lai hân hạnh phục vụ Quý khách!
Khám phá, trải nghiệm ngay
Vui lòng đăng nhập để gởi bình luận!
Đăng nhậpChưa có bình luận nào!