流萤k423 2023-12-30 07:08 采纳率: 81.4%
浏览 8
已结题

C++计算每位数字的平方和

设计一个程序,通过引用来计算一个非零整数的每一位上的数字的平方和,结果的符号由该整数的符号决定。
例如:156 的结果为 12+52+62 = 62;-156的结果为 -(12+52+62) = -62。

提示:引用仅仅是它所绑定目标的一个别名。通过取余(%)和整除(/)操作来分离一个整数每一位上的数字。在分离数字之前要先去掉该整数的符号,不能带着符号进行取余操作。

  • 写回答

2条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2023-12-30 10:20
    关注

    【以下回答由 GPT 生成】

    #include <iostream>
    #include <cmath>
    using namespace std;
    
    int main() {
        int num;
        cout << "Enter a non-zero integer: ";
        cin >> num;
    
        if (num == 0) {
            cout << "The input should be a non-zero integer." << endl;
            return 1;
        }
    
        int sum = 0;
        int temp = abs(num); // get the absolute value of the input
    
        while (temp > 0) {
            int digit = temp % 10; // get the last digit
            sum += pow(digit, 2); // add the square of the digit to the sum
            temp = temp / 10; // remove the last digit
        }
    
        if (num < 0) {
            sum = -sum; // change the sum to negative if the input is negative
        }
    
        cout << "The sum of the squares of the digits is: " << sum << endl;
    
        return 0;
    }
    

    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
    评论
编辑
预览

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 12月30日
  • 创建了问题 12月30日