【问题标题】:two-digit string addition with no number at the end两位数的字符串加法,末尾没有数字
【发布时间】:2015-01-11 00:03:05
【问题描述】:

我必须添加两个数字字符串,意思是 1234 12+34(至少这是我收集的)。我编写了一个程序,它会针对一个异常执行此操作,即当最后一个数字没有一对时,它不会正确添加。

这是我的代码:

void main()

{


char string[1000];
int count,sum=0,x,y;

printf("Enter the string containing both digits and alphabet\n");
scanf("%s",string);

for(count=0;count < string[count]; count++)
{
        x=(string[count] - '0') * 10;
        y=(string[count+1] - '0') + x;
        sum += y;
        count++;      
}

printf("Sum of string in two digit array is =%d\n",sum);

}

所以基本上如果我有 123,程序执行 12+(30-48),而不是 12+3。我已经坐了一段时间,不知道如何解决这个问题,欢迎任何提示或建议。

(像 1234 或 4567 这样的字符串将执行 12+34 和 45+67)

【问题讨论】:

  • count &lt; string[count]??
  • 12 的输入会做什么?或1234567?
  • count
  • containing both digits and alphabet ??
  • 它也会添加字母,但我只需要它来添加数字

标签: c string addition


【解决方案1】:
#include <stdio.h>
#include <ctype.h>

int main(void){
    char string[1000];
    char digits[3] = {0};
    int i, j, x, sum = 0;

    printf("Enter the string containing both digits and alphabet\n");
    scanf("%999s", string);
    for(j = i = 0; string[i]; ++i){
        if(isdigit(string[i])){
            digits[j++] = string[i];
            if(j==2){
                sscanf(digits, "%d", &x);
                sum += x;
                j = 0;
            }
        }
    }
    if(j==1){
        digits[j] = 0;
        sscanf(digits, "%d", &x);
        sum += x;
    }
    printf("Sum of string in two digit array is = %d\n", sum);
    return 0;
}

【讨论】:

  • 哇,谢谢。您不必费力地编写整个内容,但这正是我需要它做的事情。
猜你喜欢
  • 2014-03-06
  • 2021-02-14
  • 2017-09-29
  • 1970-01-01
  • 1970-01-01
  • 2010-09-21
  • 2015-09-14
  • 2015-02-02
  • 1970-01-01
相关资源
最近更新 更多