我一直在尝试对计算器进行编程,但遇到了一个我无法修复的错误。一旦我输入要完成的计算,就会出现分段错误。我认为分段错误是内存不足,所以我尝试删除我的两个循环,假设它们是问题,但没有运气。
会不会是我的 malloc?
int calculator()
{
int exit = (int *)malloc(sizeof(int));
exit = 1;
while(exit == 1){
printf("Welcome to the calculator, please enter the calculation you wish to make, if you wish to exit type EXIT\n");
float *num1 = (float *)malloc(sizeof(float));
float *num2 = (float *)malloc(sizeof(float));
char operation = (char *)malloc(sizeof(char));
float *ans = (float *)malloc(sizeof(float));
char *string = (char *)malloc(10*sizeof(char));
scanf("%s", &string);
int result = strncmp(string, "EXIT", 10);
if(result == 0){
exit = 0;
}
else{
//scanf("%f%c%f", &num1, &operation, &num2);
int length = strlen(string);
int i;
for(i = 0; i <= length; i++){
printf("forever");
if(isdigit(string[i]) != 0){
num1 = string[i];
}
else{
operation = string[i];
}
}
printf("num1%f\n", num1);
printf("operation%c\n", operation);
printf("num2%f\n", num2);
if(operation == '+'){
*ans = *num1 + *num2;
}
if(operation == '-'){
*ans = *num1 - *num2;
}
if(operation == '/'){
*ans = *num1 / *num2;
}
if(operation == '*'){
*ans = *num1 * *num2;
}
if(operation == '^'){
*ans = (float)pow(*num1,*num2);
}
printf("Your answer is %f\n", ans);
}
}
return 0;
}
样本输出:
欢迎使用计算器,请输入您要进行的计算,如果您要退出类型 EXIT 5+9 Segmentation fault (core dumped) Process returned 139(0x8B) 执行时间:2.611s
我使用 malloc 的原因是因为我分配给变量的值在我退出 for 循环时丢失了。虽然这并没有解决问题,但我觉得我的代码存在根本性的问题。