Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 606bcf8

Browse files
committed
Digits
1 parent e3eec75 commit 606bcf8

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

‎OOP1-Lab3/Digits.cpp‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,42 @@
33
//Program to input a number and then calculate sum of its digits.
44

55
#include <iostream>
6+
#include<string>
7+
#include<cctype>
8+
69
using namespace std;
7-
int main() {
10+
11+
void DigitsSum() {
12+
13+
cout << "Please enter a number that I can sum of their digit" << endl;
14+
string CusInput;
15+
int Sum = 0;
16+
bool Isvaild = 1;
17+
18+
while (1) {
19+
cin >> CusInput;
20+
for (char c : CusInput) {
21+
if (isdigit(c)) {
22+
int num = static_cast<int>(c - '0');
23+
Sum = Sum + num;
24+
}
25+
else {
26+
cout << "The input is invalid, please enter again" << endl;
27+
Isvaild = 0;
28+
break;
29+
}
30+
Isvaild = 1;
31+
}
32+
if (Isvaild) {
33+
cout << "The sum of the digits is " << Sum << endl;
34+
break;
35+
}
36+
}
837

38+
}
939

40+
int main() {
41+
42+
DigitsSum();
1043
return 0;
1144
}

‎OOP1-Lab3/README.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,22 @@
1717
3. Program to input a number and then calculate sum of its digits.
1818
- Hint: let number = 562. Then you should print 5 + 6 + 2 = 13.
1919

20+
**#include<cctype> isdigit()**
21+
22+
The functions determine whether the character is an integer.
23+
24+
**Using mod to get a last number of a integer**
25+
26+
sum = sum + a % 10;
27+
28+
a = a / 10;
29+
30+
**static_cast**
31+
32+
int num = static_cast<int>(c - '0');
33+
34+
The function will cast character c to a ASCII value like 5 is "53".
35+
2036
4. Program to find whether given number is a prime number or not.
2137

2238
5. Program to display sum of series 1 + 1/2 + 1/3 + ... + 1/n.

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /