简体   繁体   English

在 C++ 中查找数字的总和。 不同的方法

[英]Finding the sum of digits in c++. Different method

I am new to c++ and having trouble with a simple programme I need to find the sum of digits I can do that in python but I don't know how to do the same in c++.我是 C++ 的新手,在使用一个简单的程序时遇到了麻烦,我需要找到我可以在 python 中做到的数字总和,但我不知道如何在 C++ 中做同样的事情。

digits = "1234"
sum = 0
for digit in digits:
    sum += int(digit)
print(sum)

How to do the same in c++?如何在 C++ 中做同样的事情?

I tried to do the same in c++ but ends up in a error.我试图在 C++ 中做同样的事情,但最终出错了。

string digits = "1234";
int sum, i;
for(i=0;i<digits.length();i++){
    sum += stoi(digits[i]);
}

But this doesn't work但这不起作用

string digits = "1234";
int sum = 0;
for(int i = 0; i < digits.length(); i++){
    sum += digits[i] - '0';
}

Characters have their numbers ( ord ).字符有它们的编号( ord )。 By working with characters in C++ you actually work with these numbers (so char is an integer type).通过在 C++ 中处理字符,您实际上可以处理这些数字(因此char是整数类型)。 For '0' it's some number, for '1' it's 1 + '0' , for '2' it's 2 + '0' and so on.对于'0'它是一些数字,对于'1'它是1 + '0' ,对于'2'它是2 + '0'等等。 So by subtracting '0' you get the right digit.因此,通过减去'0'您会得到正确的数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM