write a Java program called SumOfDigits which reads an integer between 0 and 1000 and adds all the digits in the integer.
时间: 2024-02-18 19:04:15 浏览: 186
Sure, here's the Java program to solve your problem:
```
import java.util.Scanner;
public class SumOfDigits {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer between 0 and 1000: ");
int num = input.nextInt();
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
System.out.println("The sum of the digits is " + sum);
}
}
```
This program prompts the user to enter an integer between 0 and 1000 and then uses a while loop to add up all the digits in the integer. The program then prints out the sum of the digits.
相关问题
Write a program which reads an integer and prints sum of its digits.c++
当你想要编写一个C++程序,用于读取一个整数并计算其各个数字之和,你可以参考以下步骤和代码示例:
```cpp
#include <iostream>
// 函数用于获取一个整数的各位数字之和
int sumOfDigits(int num) {
int sum = 0;
while (num != 0) {
sum += num % 10; // 取余数得到最后一位,加到总和上
num /= 10; // 除以10去掉最后一位
}
return sum;
}
int main() {
int input;
std::cout << "请输入一个整数: ";
std::cin >> input;
// 计算输入整数的每一位数字之和
int digitSum = sumOfDigits(input);
std::cout << "该整数各位数字之和为: " << digitSum << std::endl;
return 0;
}
```
在这个程序中,首先定义了一个函数`sumOfDigits`接受一个整数作为输入,并通过不断地取余数和整除的方式逐位累加数字。然后,在`main`函数中,从用户那里接收输入,调用这个函数并将结果输出。
用c++写In the online judge system, a judge file may include multiple datasets to check whether the submitted program outputs a correct answer for each test case. This task is to practice solving a problem with multiple datasets. Write a program which reads an integer x and print it as is. Note that multiple datasets are given for this problem. 输入 The input consists of multiple datasets. Each dataset consists of an integer x in a line. The input ends with an integer 0. You program should not process (print) for this terminal symbol. 输出 For each dataset, print x in the following format: Case i: x where i is the case number which starts with 1. Put a single space between "Case" and i. Also, put a single space between ':' and x.
以下是用 C++ 编写的解题代码:
```c++
#include <iostream>
using namespace std;
int main() {
int x, i = 1;
while (cin >> x && x != 0) {
cout << "Case " << i << ": " << x << endl;
i++;
}
return 0;
}
```
这个程序使用了一个 while 循环来不断读入输入数据,直到读入的数据为 0 为止。在循环中,我们输出当前的 case 编号和输入的整数值。需要注意的是,每个 case 编号后面要输出一个冒号和一个空格。
在输出时,我们使用了 `endl` 来输出一个换行符。这样做可以确保每组数据的输出都占用一行,并且在输出结束后换行,方便阅读。
阅读全文