我正在尝试用 C 语言将字符串中的所有数字相加。例如,12abc4 应产生 16 (12+4)。你能帮我完成吗?
我现在的代码是:
#include <stdio.h>
#include <stdlib.h>
void function(char a[])
{
char sum=0;
int count=0;
for(int i=0;a[i]!='\0';i++)
{
if(a[i]>='a'&&a[i]<='z')
{
continue;
}
else
{
if(a[i+1]>='a'&&a[i+1]<='z')
{
sum=sum+a[i];
}
else
{
}
}
}
printf("%c",sum);
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
char a[100001];
scanf("%s",a);
function(a);
printf("\n");
}
}
最佳答案
您的代码存在许多问题。首先,您混淆了 char
类型(可打印字符的表示,例如数字 '3'
) 和 int
类型(表示数字的实际值,并存储为二进制值)。在您的代码中,您尝试对前求和,其中(假设 ASCII 表示),字符 2
的值为 50
。我们可以通过简单地减去 '0'
字符 (ASCII 48
) 的值来轻松解决此问题,因为 C 标准保证数字将由连续的、递增的值表示。
另一个问题是您的代码将添加每个单个数字,因此字符串中的12
将被总结为1 + 2
,而不是 12
。为了解决这个问题,我们可以保留一个“标志”来跟踪我们当前是否在某个数字“内部”,如果是,则首先将当前数字乘以 10,然后再添加新数字.
此外,您应该使用标准的 isdigit()
函数来检查字符是否是(不是)十进制数字,而不是检查特定范围的非数字字符。
您的代码中还存在一些其他问题,我已在下面发布的“工作版本”的评论中解决了这些问题:
#include <stdio.h> // This header for "printf" and "scanf"
#include <ctype.h> // This one for the "isdigit" function!
void function(char a[])
{
// char sum = 0; // Let's use an int for the sum!
int sum = 0, add = 0; // ... and another one for each extracted number to add
// int count = 0; // This is never used
int in_number = 0; // We need a flag to see if we're currently processing a number
for (int i = 0; a[i] != '\0'; i++) {
// if (a[i] >= 'a' && a[i] <= 'z') {
if (!isdigit(a[i])) { // This is better than testing individual character ranges!
if (in_number) { // We have a number to add to our total...
sum += add;
}
add = 0; // Reset the 'next' number to add
in_number = 0; // and clear our 'in_number' flag
// continue; // We don't need this, because the "else" block won't run if we're in here!
}
else { // We've found a digit ...
add *= 10; // First, multiply our current number by 10 (before we add the next digit)
add += a[i] - '0'; // We need to convert the character to a number
in_number = 1; // Don't forget to set our flag to show we're currently in a number!
}
}
// When we've finished our loop, we need to check if we're still inside a number:
if (in_number) {
sum += add;
}
printf("%d", sum); // Use the "%d" format to print an integer!
}
int main()
{
int t;
scanf("%d", &t);
while (t--) {
char a[1000]; // DO you REALLY need a 10001 character buffer?
scanf("%s", a);
function(a);
printf("\n");
}
return 0; // Always good practice to actually have this at the end of your "main"
}
请随时要求任何进一步的澄清和/或解释。
关于c - 如何在字符串中添加数字? (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63980014/