gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
input an int,return the sum of every digits,use cpp
- User
input an int,return the sum of every digits,use cpp
- Assistant
Here is the CPP code to input an integer, return the sum of its digits:
#include <iostream> int sumOfDigits(int num) { int sum = 0; // Take the absolute value of the number to handle negative numbers num = abs(num); while(num > 0) { int digit = num % 10; sum += digit; num /= 10; } return sum; } int main() { int num; std::cout << "Enter an integer: "; std::cin >> num; int sum = sumOfDigits(num); std::cout << "Sum of digits: " << sum << std::endl; return 0; }In this code, we define a function
sumOfDigitsthat takes an integernumas input and returns the sum of its digits. We first take the absolute value of the number to handle negative numbers. Then, we iterate over each digit by continuously dividing the number by 10 and taking the remainder. We add each digit to the sum and update the number by dividing it by 10. Finally, we return the sum.In the
mainfunction, we take an integer input from the user usingcin, call thesumOfDigitsfunction to get the sum of digits, and then display the result usingcout.