gpt4 book ai didi

c - 如何对字符串数组求和?

转载 作者:行者123 更新时间:2023-11-30 20:22:04 25 4
gpt4 key购买 nike

我需要编写一个程序,可以计算一个由重量及其单位组成的字符串,例如:“10,kg,500,g,0.5,t”,并将其转换为重量的总和。不过,它必须首先将不同的重量转换为千克。这是我到目前为止转换克数所得到的结果,但它不起作用。我正在使用 C。

double total_weight_kg(String s) {         
Array a = sa_of_string(s);
Array w = da_of_string(s);
double gram = 0;
int n = a_length(a);
for (int i = 0; i < n; i++) {
if (i == 'g') {
gram += get(double, w, i = i - 1);
}
}
return gram * 0.001;
}

最佳答案

如果字符串格式是固定的,您可以使用 sscanf() 从中读取值。

double total_weight_kg(String s) {
double kg = 0.0;
double g = 0.0;
double t = 0.0;

//Assuming "<kg_val>, kg, <g_val>, g, <t_val>, t" format.
sscanf("%lf, kg, %lf, g, %lf, t", &kg, &g, &t);

kg += (g/1000.0) + (t*1000.0);

return kg;
}

更新1:我看到this conversion 。为了在我的回答中明确起见,我假设“吨”而不是“吨”。对于“ton”,您可以使用此程序。

double total_weight_kg(String s) {
double kg = 0.0;
double g = 0.0;
double t = 0.0;

//Assuming "<kg_val>, kg, <g_val>, g, <t_val>, t" format.
sscanf("%lf, kg, %lf, g, %lf, t", &kg, &g, &t);

kg += (g/1000.0) + (t*907.185);

return kg;
}

更新2如果我必须在字符串中添加重量,例如“9, kg, 8, g, 0.2, t, 733, g, 1, t, 17.5, kg”或“0.1, g, 9.7, kg”,我会使用以下程序。

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

double total_weight_kg(char* s)
{
double kg = 0.0;
double wieght_val = 0.0; //If you want to use array, make this an array, store value in diff indices and add them at the end.
char wieght_unit[4] = ""; //Max string is "kg,".
char *str = s;


while(0 < strlen(str))
{
sscanf(str, "%lf, %s,", &wieght_val, wieght_unit);
printf("Read: %lf, %s\n", wieght_val, wieght_unit);

if(!strcmp(wieght_unit, "kg,") || !strcmp(wieght_unit, "kg"))
kg += wieght_val;
else if(!strcmp(wieght_unit, "g,") || !strcmp(wieght_unit, "g"))
kg += wieght_val / 1000.0;
else if(!strcmp(wieght_unit, "t,") || !strcmp(wieght_unit, "t"))
kg += wieght_val * 1000.0; //OR 907.185

//Update string pointer.
str = strstr(str, wieght_unit);
str += strlen(wieght_unit);

//Resetting values.
strcpy( wieght_unit, "");
wieght_val = 0.0;
}

return kg;
}

int main() {

printf("Weight is %lf kg\n", total_weight_kg("9, kg, 8, g, 0.2, t, 733, g, 1, t, 17.5, kg"));

return 1;
}

输出:

Read: 9.000000, kg,                                                                                                                             
Read: 8.000000, g,
Read: 0.200000, t,
Read: 733.000000, g,
Read: 1.000000, t,
Read: 17.500000, kg
Weight is 1227.241000 kg

关于c - 如何对字符串数组求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40891659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com