gpt4 book ai didi

c中的字符算术;总线错误

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

我的程序应该接受 2 个字符串并进行算术运算。

示例:

输入:abc+aab

输出:abc + aab => bce

该程序获取用户输入字符串并将这两个部分加载到一个多维数组和一个用于算术符号的 char 变量中。它应该将字符转换为它们的等值数字(ASCII)来进行算术。然后它应该再次将值作为字符输出。当数值超过 26 时,它将从字符串的第一部分获取字符并输出其大写形式。

示例:

输入:d+y

输出:d + y => D

这看起来很简单,但我对 java 更有经验,我认为我的代码中存在翻译丢失,导致运行时错误:总线错误 第 44 行:if (a[2][i] >= 27){

仅供引用,当我编译时输入:gcc -g -o prog06 prog06.c -lm

然后使用 gdb 运行我输入:gdb prog06

到目前为止的代码:

/* My Name
C & Unix
prog06
*/

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

main() {
int i, j, k, a[3][9];
char input[19], b, c[10];
system("clear");

printf("This is a string arithmatic program of SOS form.\n");

input:
printf("Input: ");
scanf("%s", input);
for (i = 0; i < strlen(input); i++){
if (input[i] != '+' || input[i] != '-' || input[i] != '/' || input[i] != '*'){
a[j][k] == input[i] - '`';
k++; //Converts input to a multidimensional string array
continue; //a[][] + char b for arithmatic character.
}
if (input[i] == '+' || input[i] == '-' || input[i] == '/' || input[i] == '*'){
a[j][k+1] = '\0';
b = input[i];
j++;
k = 0;
continue;
}

}
if (b == '+') goto add;
if (b == '-') goto sub;
if (b == '/') goto div;
if (b == '*') goto mul;

add:
i = 0;
do {
a[2][i] = a[0][i] + a[1][i];
if (a[2][i] >= 27){
a[2][i] = a[0][i] + 64;
}
i++;
} while (a[0][i] != '\0' || a[1][i] != '\0'); j = i;
printf("\n%s + %s => ", a[0], a[1]);
goto output;

sub:

div:

mul:

output:
for (i = 0; i < j; i++){
c[i] = a[2][i];
}
printf("%s", c);
}

最佳答案

要修复的示例

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

int main(void) {
int i, j, k, a[3][9];
char input[19], b, c[10];
system("clear");

printf("This is a string arithmatic program of SOS form.\n");

input:
printf("Input: ");
scanf("%18s", input);
for(k = j = i = 0; input[i]; ++i){
if(islower(input[i])){
if(j == 0)
a[2][k] = input[i];
a[j][k++] = input[i] - 'a' + 1;
} else if(strchr("+-/*", input[i])){
b = input[i];
++j;//! Operator is assumed one
k = 0;
} else {
//Illegal characters are present
goto error_proc;
}
}
if (b == '+') goto add;
if (b == '-') goto sub;
if (b == '/') goto div;
if (b == '*') goto mul;

error_proc:
while(getchar()!='\n');
goto input;

add:
for(i=0; i < k; ++i){//! k : it's assuming the length of the operand is equal
if(a[2][i] + a[1][i] > 'z')
a[2][i] = toupper(a[2][i]);
else
a[2][i] = 'a' + a[0][i] + a[1][i] - 1;
}
goto output;

sub:
goto end;
div:
goto end;
mul:
goto end;

output:
for(i = 0; i < k; ++i){
c[i] = a[2][i];
}
c[i] = '\0';
printf("%s", c);

end:
return 0;
}

关于c中的字符算术;总线错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26151829/

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