[英]C Language - add products’ digits (i.e., not the products themselves)
I am looking to calculate the below sum but using the products digits, not the products themselves: 我希望计算以下总和,但要使用产品数字,而不是产品本身:
These are the initial values: 这些是初始值:
2 + 12 + 8 = 22 2 + 12 + 8 = 22
but what I want to achieve is the following, so that the digit 12 is actually seen as a 1 and a 2 separately 但是我想要实现的是以下内容,因此数字12实际上被分别视为1和2
2 + 1 + 2 + 8 = 13 2 + 1 + 2 + 8 = 13
Using C language is there a formula in which I can use to perform this task? 使用C语言是否可以使用公式来执行此任务?
Supposing you have an array of the values you can do : 假设您可以执行一组值:
#include <stdio.h>
unsigned sum(const unsigned * a, size_t sz)
{
unsigned sum = 0;
while (sz--) {
unsigned v = *a++;
while (v) {
sum += v%10;
v /= 10;
}
}
return sum;
}
int main()
{
const unsigned a[] = { 2, 12, 8 };
printf("sum = %u\n", sum(a, sizeof(a)/sizeof(*a)));
}
Compilation and execution : 编译执行:
/tmp % gcc -pedantic -Wextra s.c
/tmp % ./a.out
sum = 13
If +
is the only other token, then you can disregard it and merely sum the digits on the stream. 如果
+
是唯一的其他标记,则可以忽略它而仅将流中的数字求和。 So 所以
#include <stdio.h>
#include <ctype.h> // for isdigit
int main(void)
{
char* s = "2 + 12 + 8";
int total = 0;
for (; *s; ++s){
if (isdigit((unsigned char)*s)){
total += *s - '0';
}
}
printf("%d\n", total);
}
is one way. 是一种方式。
*s - '0';
is the idiomatic way of transforming a char
digit to its numerical value. 是将
char
转换为数值的惯用方式。 The loop termination condition is the NUL terminator in the string s
. 循环终止条件是字符串
s
的NUL终止符。
This is most certainly not the best approach if you want other operators between terms. 如果您希望在术语之间使用其他运算符,这当然不是最佳方法。 At that point you need to build a full expression parser (such as one based on the worked example in Kernighan & Ritchie).
到那时,您需要构建一个完整的表达式解析器(例如基于Kernighan&Ritchie中的示例的解析器)。
There is no direct formula for this task but you can perform this task in a separate function and use that function wherever it is needed. 此任务没有直接公式,但是您可以在单独的函数中执行此任务,并在需要时使用该函数。 Here are two simple solutions which depend on the type of input.
这是两个简单的解决方案,具体取决于输入的类型。
If Input is in the form of String (ie "2 + 12 + 8") then the code will be - 如果Input为String形式(即“ 2 + 12 + 8”),则代码为-
#include <stdio.h>
int main()
{
char str[] = "2 + 12 + 8";
int sum=0;
for (int i = 0; i < strlen(str); i++) {
if (str[i] >= '0' && str[i] <= '9')
sum += str[i] - '0';
}
printf("%d",sum);
return 0;
}
If Input is in the form of Array (ie [2, 12, 8]) then the code will be - 如果Input为Array形式(即[2,12,8]),则代码为-
#include <stdio.h>
int main()
{
int num[] = {2, 12, 8};
int sum=0;
int length = sizeof(num) / sizeof(num[0]);
for (int i = 0; i < length; i++) {
while (num[i]) {
sum += num[i] % 10;
num[i] /= 10;
}
}
printf("%d",sum);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.