【发布时间】:2014-10-01 22:37:50
【问题描述】:
我的程序应该接受 2 个字符串并进行算术运算。
例子:
输入:abc+aab
输出:abc + aab => bce
程序获取用户输入的字符串并将两部分加载到多维数组和算术符号的 char 变量中。 它应该将字符转换为它们的数字等价(ASCII)来进行算术。 然后它应该再次将值输出为字符。当数值超过 26 时,它会从字符串的第一部分获取字符并输出其大写形式。
例子:
输入:d+y
输出:d + y => D
这看起来很简单,但我对 java 的经验更丰富,我认为我的代码中存在翻译丢失导致运行时错误:总线错误 在第 44 行:如果 (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);
}
【问题讨论】:
-
考虑什么是好的"Minimal, Complete, and Verifiable Example"。当您想要了解崩溃时,您已经发布了整个程序和遇到的问题。如果你的程序只做加法,它还会崩溃吗?如果是这样,为什么您的问题中应该有其他操作的代码?你为什么要向我们展示你打印出一个程序“横幅”......没有它你有问题吗?标题评论?尝试将您的程序简化为显示崩溃的基本情况,您可能会在此过程中自己解决它...
-
j, k需要初始化。 -
你声称在 Java 方面更有经验,并且在 C 中使用
goto。对... -
之所以有其他代码,是因为程序期望在用户输入+-\或*时能够进行算术运算。除了 add 之外,我还没有添加任何其他函数的代码,因为我想先让它工作
-
而且我不太明白 goto 是如何成为 C 的高级功能的。我想我是从互联网上学到的。它非常类似于在 MIPS 中使用跳转和链接