用于计算字符串中所有整数总和的 C 语言程序


2022年4月20日, Learn eTutorial
2510

如何计算字符串中整数的个数并求其总和?

在这个 C 语言程序中,我们需要计算字符串中整数的个数及其总和。例如,考虑字符串 "learn C programming 12",其中有两个整数,所以我们将计数记为 '2',整数的总和为 '1 + 2 = 3'。

为了在 C 语言中实现这个程序逻辑,我们从用户那里接收一个包含整数和字母的值。启动一个从零到字符串末尾的 for 循环来检查是否存在任何整数。然后在 for 循环内部,使用 'if' 条件检查字符串字符是否大于零且小于或等于 9。如果是,则将计数器加 1,并将该数字加到总和中。最后,我们显示输出结果,即字符串中整数的总和,包括总和计数

if 条件语句的语法是。


if (testExpression) {

  // codes inside the body of if

} 

如果测试表达式为真,我们执行 if 语句。但如果测试表达式为假,我们则跳过 if 语句内的代码。

算法

第 1 步: 包含头文件,以便在 C 程序中使用内置函数。

第 2 步: 声明整型变量 countncsum,并设置 nc=0sum=0

第 3 步: 声明一个字符类型的变量。

第 4 步: 从用户处读取输入到变量 string 中。

第 5 步: 使用 for 循环设置 count=0,检查 str[count]!='\0',然后执行第 6 步。

第 6 步: 检查 str[count]>0str[count]<=9,如果是,则 nc=nc+1sum=sum+str[count]-0

第 7 步: 将字符串中的数字个数显示为 NC

第 8 步: 将所有数字的总和显示为 sum


要在 C 语言中计算字符串中的整数个数,我们需要学习以下主题,请参考这些内容以获得更好的理解。

C 语言源代码

                                          #include <stdio.h>

void main() {
  char str[80];
  int count, nc = 0, sum = 0;
  printf("Enter the string containing both digits and alphabet\n");
  scanf("%s", & str);
  for (count = 0; str[count] != '\0'; count++) /* check the string for any integers */ {
    if ((str[count] >= '0') && (str[count] <= '9')) /* check and add the integers  in to a variable called sum  */ {
      nc += 1;
      sum += (str[count] - '0');
    } /* End of if */
  } /* End of For */
  printf("NO. of Digits in the string=%d\n", nc);
  printf("Sum of all digits=%d\n", sum);
} /* End of main() */
                                      

输出

Enter the string containing both digits and alphabet
goodmorning25

NO. of Digits in the string=2
Sum of all digits=7