gpt4 book ai didi

c - 使用字符串查找数字平均值

转载 作者:太空宇宙 更新时间:2023-11-04 04:55:45 24 4
gpt4 key购买 nike

作为学习练习,我正在创建一个程序,将通过 argv[1] 输入的字符转换为整数。该程序然后找到整数的数字平均值。

例如:abc 将是 123,并且 1+2+3 = 6,其中 6 是数字平均值。该程序的第一部分可以运行,但我无法正确编码找到数字平均值的部分。

word abc 的输出应该是 123 6;相反,它是 123 150


编辑:已解决!

#include <stdio.h>
#include <strings.h>

int main(int argc, char *argv[])
{
char stra[27], strb[0];
int str_num, str_len;
int final = 0;

if (argv[1][0] < 'a')
{
printf("!Argument missing!");
return 0;
}

strcpy(stra, argv[1]);
str_len = strlen(stra);

for (str_num = 0; str_num < str_len; str_num++)
{
if (stra[str_num] <= 'z' && stra[str_num] >= 'a')
{
strb[str_num] = (stra[str_num] - 'a' + 1) % 9 + '0';
if (strb[str_num] == '0')
{
strb[str_num] = '9';
}
}
else
{
printf("%s !Please use only the lower case!", stra);
return 0;
}
}

for (str_num = 0; str_num < str_len; str_num++)
{
final += strb[str_num] - '0';
}

printf("%s %i", strb, final);
return 0;
}

最佳答案

#include <stdio.h>
#include <strings.h>
int main(int argc, char *argv[])
{
char *stra;
char *strb;
int str_num;
int str_len;
int final;
final = 0;
if ( (argc >= 2 && argv[1][0] < 'a') || (argc <= 1))
{
printf("!Argument missing!");
return 0;
}
str_len = strlen(argv[1]);

strb = (char*) malloc((str_len+1)*sizeof(char));

for (str_num = 0; str_num < str_len; str_num++)
{
if (argv[1][str_num] <= 'z' && argv[1][str_num] >= 'a')
{
strb[str_num] = (argv[1][str_num] - 'a'+1) % 9 + '0'; //to get string with numbers from 1 to 9
}
else
{
printf("%s !Please use only the lower case!",argv[1]);
return 0;
}
}
strb[str_len] = '\0' // put the end char of the string : mandatory to print it.
for (str_num = 0; str_num < str_len; str_num++)
{
final += strb[str_num] - '0'; // count the sum of the numbers from 1 to 9 ?
}
printf("%s %i",strb,final);
free(strb);
return 0;
}

关于c - 使用字符串查找数字平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8609691/

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