我试图找到给定数字的各位数字之和。例如,134
将会得到 8
。
我的计划是使用 .to_string()
将数字转换为字符串,然后使用 .chars()
迭代每个数字字符。接下来,我想将迭代中的每个 char
转换为一个整数并将其加到一个变量中。最后,我希望获得这个变量的最终值。
我尝试使用以下代码将 char
转换为整数:
```rust let digit_char = '7'; let digit_int = digit_char.to_digit(10); ```
返回:
```rust let digit_char = '7'; let digit_int = digit_char.to_digit(10); ```
fn main() {
let x = "123";
for y in x.chars() {
let z = y.parse::<i32>().unwrap();
println!("{}", z + 1);
}
}
但它导致了这个错误:
error[E0599]: no method named `parse` found for type `char` in the current scope
--> src/main.rs:4:19
|
4 | let z = y.parse::<i32>().unwrap();
| ^^^^^
这段代码完全实现了我想要做的事情,但首先我必须将每个char
转换为字符串,然后再转换为整数,以便通过z
来增加sum
。
fn main() {
let mut sum = 0;
let x = 123;
let x = x.to_string();
for y in x.chars() {
// converting `y` to string and then to integer
let z = (y.to_string()).parse::<i32>().unwrap();
// incrementing `sum` by `z`
sum += z;
}
println!("{}", sum);
}
(游乐场)
let v: i32 = x.parse()?;
。您能否检查一下这是否与https://dev59.com/-V8d5IYBdhLWcg3wNQNg不重复? - E net4+1
不让你感到混乱吗?因为如果它能编译的话,代码会打印出“2,3,4”。 - Christopher Oezbek