Mô tả bài toán
Tạo ứng dụng Console, cho người dùng nhập vào số
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.
Cách giải quyết
Sử dụng vòng lặp while để duyệt con số:
- Lấy ký tự hàng đơn vị bằng cách lấy
r = num % 10
- Loại bỏ ký tự hàng đơn vị vừa lấy
num / 10
- Cộng dồn tất cả kết quả vào biến
sum = sum + r
Source code
[su_spoiler title="Bài giải (Nên nhớ tự làm trước khi click vào đây)"]
1/*
2C# Program to Get a Number and Display the Sum of the Digits
3This is a C# Program to get a number and display the sum of the digits.
4
5Problem Description
6This C# Program Gets a Number and Display the Sum of the Digits.
7
8Problem Solution
9The digit sum of a given integer is the sum of all its digits.
10*/
11using System;
12using System.Collections.Generic;
13using System.Linq;
14using System.Text;
15
16namespace Lession3
17{
18 class Program
19 {
20 static void Main(string[] args)
21 {
22 int num, sum = 0, r;
23 Console.WriteLine("Enter a Number : ");
24 num = int.Parse(Console.ReadLine());
25 while (num != 0)
26 {
27 r = num % 10;
28 num = num / 10;
29 sum = sum + r;
30 }
31 Console.WriteLine("Sum of Digits of the Number : " + sum);
32 Console.ReadLine();
33
34 }
35 }
36}
[/su_spolier]
Github
https://github.com/kellyfire611/learning.nentang.vn-csharp/tree/master/src/Lession3