我正在尝试在 C 中创建一个简单的计算器。我目前只有一个问题,那就是当我尝试将我的运算符值分配给输入的值时,存储在一个字符数组中,它会分配它,但是当我退出时不再分配 for 循环。我尝试过使用 malloc,但这不起作用。提前致谢
int calculator()
{
int exit;
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 num2;
char operation;
float ans;
char string[10];
int beenhere = 0;
scanf("%s", &string);
int result = strncmp(string, "EXIT", 10);
if(result == 0){
exit = 0;
}
else{
int length = strlen(string);
int i;
for(i = 0; i <= length; i++){
if(isdigit(string[i]) != 0){
if(beenhere == 0){
num1 = (float)string[i] - '0';
beenhere = 1;
}
else{
num2 = (float)string[i] - '0';
}
}
else{
operation = string[i];
}
}
printf("num1 %f\n", num1);
printf("%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;
}
编辑:我指的是forloop,其中的赋值是: operation = string[i];