你好,所以我一直在工作一个小程序,这是一种计算器(我是一个初学者),以及你可以在标题中看到,然后在代码的末尾,两个if strcmp不起作用。并且vscode告诉我(对于strcmp)异常已经发生。段错误。但是gcc告诉我标题中有什么。
#include <stdio.h>
#include <string.h>
int main()
{
float num1;
float num2;
float anwser;
int rnum = 1;
int hi = 0;
char operator;
char ifyorn;
char y = 'y';
char n = 'n';
while (hi == 0)
{
printf("Enter operator +, -, /, x: ");
scanf(" %c", &operator);
printf("Enter num %d :", rnum++);
scanf("%f", &num1);
printf("Enter num %d :", rnum++);
scanf("%f", &num2);
switch (operator)
{
case '+':
anwser = num1 + num2;
printf("Do you want to continue y/n n");
scanf(" %c", &ifyorn);
break;
case '-':
anwser = num1 - num2;
printf("Do you want to continue y/n n");
scanf(" %c", &ifyorn);
break;
case 'x':
anwser = num1 * num2;
printf("Do you want to continue y/n n");
scanf(" %c", &ifyorn);
break;
case '/':
anwser = num1 / num2;
printf("Do you want to continue y/n n");
scanf(" %c", &ifyorn);
break;
default:
printf("This is not a valid character please try again :(");
break;
}
if(strcmp (ifyorn, n) == 0)
{
printf("%f", anwser);
hi == 1;
}
if(strcmp (ifyorn, y) == 0)
{
hi == 0;
}
}
}
变量ifyorn
,y
和n
声明为char
类型。
char ifyorn;
char y = 'y';
char n = 'n';
函数strcmp
需要的参数类型为指向字符串的指针类型char *
。
那么这些if语句
if(strcmp (ifyorn, n) == 0)
和
if(strcmp (ifyorn, y) == 0)
是不正确的。你应该写
if ( ifyorn == n )
和
if ( ifyorn == y )
在这些语句中使用比较运算符而不是赋值
hi == 1;
和
hi == 0;
你需要写
hi = 1;
和
hi = 0;
增加变量rnum
看起来毫无意义
printf("Enter num %d :", rnum++);
scanf("%f", &num1);
printf("Enter num %d :", rnum++);
scanf("%f", &num2);
为什么不直接写
printf("Enter num %d :", 1 );
scanf("%f", &num1);
printf("Enter num %d :", 2 );
scanf("%f", &num2);
在default
标签下的代码片段中,您应该再添加一条语句
default:
printf("This is not a valid character please try again :(");
ifyorn = y;
break;
你不必对那家伙那么刻薄,他正在学习。
你得到这个错误是因为你传递字符给strcmp(),而不是指向字符的指针。
这里是关于该函数的更多信息。
https://www.programiz.com/c-programming/library-function/string.h/strcmp