0) { remainder = n % 1" />

编程输入一个整数怎么算

时间:2025-01-28 02:10:04 网络游戏

输入一个整数并计算其各位数字之和的方法如下:

C语言

```c

include

int main() {

int n, sum = 0, remainder;

printf("请输入一个正整数: ");

scanf("%d", &n);

while (n > 0) {

remainder = n % 10;

sum += remainder;

n /= 10;

}

printf("各位数字之和为: %d\n", sum);

return 0;

}

```

C++

```cpp

include

int main() {

int sum = 0, n;

std::cout << "请输入任意一个整数: ";

std::cin >> n;

while (n != 0) {

sum += n % 10;

n /= 10;

}

std::cout << "各位数字的和: " << sum << std::endl;

return 0;

}

```

Java

```java

import java.util.*;

public class SumOfDigits {

public static void main(String[] args) {

System.out.print("请输入任意一个整数: ");

Scanner scanner = new Scanner(System.in);

int sum = 0;

int n = scanner.nextInt();

while (n != 0) {

sum += n % 10;

n /= 10;

}

System.out.println("各位数字的和: " + sum);

}

}

```

Python

```python

n = int(input("请输入一个正整数: "))

sum_of_digits = 0

while n > 0:

sum_of_digits += n % 10

n //= 10

print("各位数字之和为:", sum_of_digits)

```

这些代码示例分别展示了如何在不同的编程语言中输入一个整数并计算其各位数字之和。你可以选择适合你的编程语言进行尝试。