c - 将 Char 与 == 和单引号进行比较会给出警告
问题描述
我正在编写一个程序来计算余弦,我应该读取用户输入的角度(°)或弧度(r)。如果角度以度为单位,则应将其转换为弧度(因此我使用了 if-else 语句)。但是,当我将 char 与==
单引号进行比较时,会收到以下警告:
warning: multi-character character constant [-Wmultichar]
if((unit != '°') && (unit != 'r'))
这是我的完整代码:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
// Prototype
void calc_cos(double, char);
int main (void)
{
double angle;
char unit;
printf("PLease give an angle and its unit in degrees (°) or radians (r) for cosinus calculation\n");
if((unit != '°') && (unit != 'r'))
{
printf("ERROR. Unit is not in '°' or 'r'. Aborting...\n");
return 0;
}
else
{
scanf("%lf %c", &angle, &unit);
calc_cos(angle, unit);
}
return 0;
}
void calc_cos(double angle, char unit)
{
double results=0;
if(unit == '°')
{
angle = angle*M_PI/180;
}
else if(unit == 'r')
{
angle = angle;
}
results = cos(angle);
printf("cos(%lf rad) = %lf\n", angle, results);
}
解决方案
正如其他人在评论中指出的那样,度数 ( °
) 字符在 ASCII 系统中未编码为单个字节;相反,它被编译器解释为(可能)两个字节的序列。
有多种解决方法。一种是使用变量的wchar_t
类型unit
,并使用相应的宽文字进行比较(L'°'
and L'r'
,代替'°'
and 'r'
);但是,这将需要(至少)更改您的scanf
调用以使用%lc
格式说明符,但在这种情况下,您几乎肯定会更好,使用标准 I/O 函数的wprintf
和wscanf
“宽字符”版本。
但是,即使进行了此类更改,您也可能会遇到°
在控制台应用程序中读取字符的问题,因为可以使用许多不同的编码系统。因此,在我看来,您最好使用一个简单的字母d
来指定度数单位。
此外,即使有任何这些修复,您的代码中也存在一些其他问题。最值得注意的是,您在unit
变量给出之前对其进行了测试。更正此问题的代码以及其他一些建议的改进(并使用d
for 度数)如下所示:
#include <stdio.h>
#include <stdlib.h>
#define _USE_MATH_DEFINES /// Many compilers require this to give the "M_PI" definition
#include <math.h>
// Prototype
void calc_cos(double, char);
int main(void)
{
double angle;
char unit;
printf("Please give an angle and its unit in degrees (d) or radians (r) for cosinus calculation\n");
scanf("%lf %c", &angle, &unit); /// MUST read "unit" BEFORE testing it!
if ((unit != 'd') && (unit != 'r')) {
printf("ERROR. Unit is not in 'd' or 'r'. Aborting...\n");
return 0;
}
calc_cos(angle, unit);
return 0;
}
void calc_cos(double angle, char unit)
{
double results = 0;
if (unit == 'd') {
angle = angle * M_PI / 180;
}
// else if (unit == 'r') { /// This block is unnecessary
// angle = angle;
// }
results = cos(angle);
printf("cos(%lf rad) = %lf\n", angle, results);
}
请随时要求任何进一步的澄清和/或解释。
推荐阅读
- javascript - JavaScript:重新创建/订购文档片段。从片段中删除格式
- python - 如何在 matplotlib.pyplot.imshow 中标记单元格(绘制单元格边框)
- javascript - 克隆 html 表单标签后不显示图像预览
- if-statement - 在 redis 调用上使用 luascript 检查 nil 不起作用
- reporting-services - 如何根据控制中断在标题中打印文本或图像
- python - Pandas - 从列中提取多个数据
- linux - grepping后如何过滤部分行
- sql - Getdate() 函数在 SQL Server 2014 Express 中不起作用
- python - 在控制台中打印,但在格式化为 CSV 时不打印
- asp.net-web-api - 通过 Axios.js 库调用 API 端点时 MessageHandler 未正确执行