求C语言思路(循环结构)

输入一个数字,如何求出该数各位上的数字和相逆位上的数字的平方和,如图所示

img

#include <stdio.h>
#include <string.h>
int main()
{
char s[100];
scanf("%s", s);
int n = strlen(s);
int sum = 0;
for (int i = 0; i <= n / 2; i++)
{
int x = (s[i] - '0') * (s[i] - '0')  + (s[n - 1 - i] - '0') * (s[n - 1 - i] - '0');
sum += x;
}
printf("%d", sum);
return 0;
}
}

#include <stdio.h>  
  
int main() {  
    int num, sum = 0;  
    printf("请输入一个数字:");  
    scanf("%d", &num);  
    while (num > 0) {  
        sum += num % 10;  
        num /= 10;  
    }  
    printf("该数各位上的数字和相反数上的数字的平方和为:%d\n", sum);  
    return 0;  
}
不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 这有个类似的问题, 你可以参考下: https://ask.csdn.net/questions/7522414
  • 这篇博客你也可以参考下:【C语言循环结构题目】输入一个无符号整数,输出它的各位数字之和
  • 你还可以看下c语言参考手册中的 c语言-内存模型与数据竞争
  • 除此之外, 这篇博客: C语言单向链表应用之多项式创建,遍历,相加中的 一、多项式创建和遍历的代码 部分也许能够解决你的问题, 你可以仔细阅读以下内容或者直接跳转源博客中阅读:
    #include<stdio.h>
    #include<stdlib.h>
    
    struct node
    {
        //指数
        int exp;
        //系数
        float coef;
        struct node *next;
    };
    
    //简写
    typedef struct node Node;
    
    //函数的声明
    Node *creatList();
    void DisList(Node *head);
    
    int main(int argc, char const *argv[])
    {
        Node *myNode;
    
        myNode = creatList();
        DisList(myNode);
        return 0;
    }
    
    /**
     * 创建多项式链表
     * 用户输入多项式每一项的系数和指数,只要二者不同时为0,则一直接收用户输入
     * @return Node* 返回创建好的链表的头指针
     */
    Node *creatList()
    {
        Node *previous, *head = NULL, *current;
        //指数
        int exp;
        //系数
        float codf;
        printf("请输入系数和指数: ");
        scanf("%f,%d",&codf,&exp);
        while(exp!=0 || codf != 0)
        {
            current = (Node *) malloc(sizeof(Node));
            current->coef = codf;
            current->exp = exp;
            current->next = NULL;
            //如果头指针是空,则把当前结点赋值给头指针
            if(head == NULL)
            {
                head = current;
            }
            //如果不是头指针,则把当前结点链接在先前结点后面
            else
            {
                previous->next = current;
            }
            //先前结点变为当前结点
            previous = current;
            printf("请输入系数和指数: ");
            scanf("%f,%d",&codf,&exp);
            
        }
        return head;
    
    }
    
    /**
     * 多项式链表的遍历
     * 输入多项式的每一个元素
     * @Node *head, 需要遍历链表的头指针
     */
    void DisList(Node *head)
    {
        Node *p = head;
        while(p)
        {
            printf("%.2f X^%d",p->coef,p->exp);
            if(p->next != NULL)
            {
                printf(" + ");
            }
            p = p->next;
        }
    }
    
    
  • 您还可以看一下 徐家乾老师的极简C语言入门课程课程中的 解决实际问题的程序设计方法小节, 巩固相关知识点
  • 以下回答来自chatgpt:

    很抱歉,我不清楚您具体想要解决的问题是什么,也不知道您想要的输入和输出格式是怎样的。请提供更具体的信息,我将尽我所能为您提供帮助。


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