字符串的总和

时间:2016-06-20 23:15:05

标签: c

我必须编写一个函数来查找字符串中数字的总和。需要为main中的每一行打印总和。我使用strtok和token来删除逗号。然后atof将字符串转换为double。我很难把这些碎片连接起来。

#include <stdio.h>
int main(void) {
    int i;
    double sum=0;

    char* str[] = {"12, 34, 56, 78",
        "82.16, 41.296",
        "2, -3, 5, -7, 11, -13, 17, -19",
        "9.00009, 90.0009, 900.009, 9000.09, 90000.9"};

    for(i=0;i<(sizeof(str)/sizeof(*str));i++)
    {
        //print//
        printf("sum = %3.6f \n",sum);
    }
 }

double sum(char* s[])
{
    const char str[100];
    char *token;
    char *del = ", ";

    token = strtok(str, del);

    while( token != NULL )
    {
        token = strtok(NULL, del);
    }

    double atof( const char *s
    double n;
    double sum=0;
    for(n=0;n<str(s);n++)
    {
        sum = sum + s[n];
    }
    return (sum);
  }

1 个答案:

答案 0 :(得分:0)

ideone.com/3umold - BLUEPIXY

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

double sum(const char s[]);

int main(void) {
    int i;
    //double sum=0;

    char* str[] = {
        "12, 34, 56, 78",
        "82.16, 41.296",
        "2, -3, 5, -7, 11, -13, 17, -19",
        "9.00009, 90.0009, 900.009, 9000.09, 90000.9"
    };

    for(i = 0; i < sizeof(str)/sizeof(*str); i++){
        //print
        printf("sum = %f \n", sum(str[i]));
    }

    return 0;
}

double sum(const char s[]){
    char str[100];
    char *token, *del = ", ";
    double sum = 0.0;

    strcpy(str, s);
    token = strtok(str, del);

    while( token != NULL ){
        sum += atof(token);
        token = strtok(NULL, del);
    }
    return sum;
}