首页 > 解决方案 > 将 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);
}

标签: ccharcomparisonsingle-quotes

解决方案


正如其他人在评论中指出的那样,度数 ( °) 字符在 ASCII 系统中未编码为单个字节;相反,它被编译器解释为(可能)两个字节的序列。

有多种解决方法。一种是使用变量的wchar_t类型unit,并使用相应的宽文字进行比较(L'°'and L'r',代替'°'and 'r');但是,这将需要(至少)更改您的scanf调用以使用%lc格式说明符,但在这种情况下,您几乎肯定会更好,使用标准 I/O 函数的wprintfwscanf“宽字符”版本。

但是,即使进行了此类更改,您也可能会遇到°在控制台应用程序中读取字符的问题,因为可以使用许多不同的编码系统。因此,在我看来,您最好使用一个简单的字母d来指定度数单位。

此外,即使有任何这些修复,您的代码中也存在一些其他问题。最值得注意的是,您在unit变量给出之前对其进行了测试。更正此问题的代码以及其他一些建议的改进(并使用dfor 度数)如下所示:

#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);
}

请随时要求任何进一步的澄清和/或解释。


推荐阅读