gpt4 book ai didi

谁能用c语言为我简化这段代码?

转载 作者:行者123 更新时间:2023-11-30 14:36:32 25 4
gpt4 key购买 nike

n的所有奇数位之和。(例如n是32677,则和为3+7+7=17)

这是代码。对于这个问题,任何循环或函数都是可以接受的,但不能长于这个答案。

#include <stdio.h>
int main()
{
char n[20];
int m=0,i;
printf("Enter integers for the variable n: ");
for (i=0;i<20;i++)
{
scanf("%c",&n[i]);
if(n[i]=='\n')
{
break;
}
}
for (i=0;i<20;i++)// this is the part I would like to simplified
{
if (n[i]%2!=0)
{
if(n[i]==49)
m++;
if(n[i]==51)
m+=3;
if(n[i]==53)
m+=5;
if(n[i]==55)
m+=7;
else if(n[i]==57)
m+=9;
}
}
printf("The sum of odd digits of n is %d.",m);
}

最佳答案

以下是您可以使用的一些工具/想法:

  • ctype.h 中有一个函数 isdigit(),它告诉您一个字符是否代表数字。
  • 假设数字0..9的字符按顺序排列,则字符数字c表示的值为c-'0'

关于谁能用c语言为我简化这段代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57997021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com