如何纠正C中的多字符错误?

时间:2014-10-13 06:44:03

标签: c

以下是我的尝试:

#include<stdio.h>

int main()
{
    int count=0;
    int x;
    char Grade;
    char studentName[50];
    int studentID=0;
    int f=0;

    do
    {
        printf("\nEnter student ID: ");
        scanf("%d", &studentID);

        if(studentID!=0)
        {           
            printf("Enter student name: ");
            scanf("%s", &studentName);
            printf("Enter student marks: ");
            scanf("%d", &x);

            if(x<=100 && x>=80)
                Grade = 'A';
            else if(x<=79 && x>=75)
                Grade = 'A-';
            else if(x<=74 && x>=70)
                Grade = 'B+';
            else if(x<=69 && x>=65)
                Grade = 'B';
            else if(x<=64 && x>=60)
                Grade = 'B-';
            else if(x<=59 && x>=55)
                Grade = 'C+';
            else if(x<=54 && x>=50)
                Grade = 'C';
            else if(x<=49 && x>=45)
                Grade = 'C-';
            else if(x<=44 && x>=40)
                Grade = 'D+';
            else if(x<=39 && x>=35)
                Grade = 'D';
            else if(x<=34 && x>=30)
                Grade = 'D-';
            else if(x<=29 && x>=0)
            {
                Grade = 'F'; 
                f++;
            }   
            printf("%s have the following marks %d and the Grade is %c\n ", studentName, x, Grade);
            count++;        
        }   
    }while(studentID!=0);

    printf("Sum of student =  %d\n", count);
    printf("Sum of fail student = %d\n", f);
}

尝试编译时出现以下错误:

"[Warning] multi-character character constant [-Wmultichar]".

我可以执行代码,但错误一直困扰着我。另外,我无法得到结果 - 等级。

请提出建议,因为我是新学员。感谢。

2 个答案:

答案 0 :(得分:2)

正如所指出的那样,错误是你试图将2 char强制转换为只能包含1的变量,这就是为什么你不能用&#34; - &#34;和我想你不会有&#34; +&#34;在您的情况下(参见@mafso评论),程序似乎只接受第一个char(字母),其余部分丢失。

让编译器为您调整容器的大小:

// With "[]", the compiler will reserve just what we need
const char * grades[] = 
{
    "F", "D-", "D", "D+", "C-", /* etc... */ "A-", "A+"
};

另外,我认为我们可以做一些数学技巧直接从评级中获得字符串等级并避免&​​#34;瀑布&#34; else if

size_t index;

if(x < 25)    // Safety measure
{
    index = 0; // F
}
else if (x > 79) // [edit] ok we need another one
{
    index = 11; // A (or should it be A+ ?)
}
else // The real trick
{
    index = (x/5 + 1) - 6 ;
}

// You need 3 chars: one for the letter, one for the + (or -) and the
// last one for the NULL-terminating '\0' which is the "end-of-string" byte
char student_grade[3];
strcpy(student_grade, grades[index]);

现在您了解我从grades"F-"开始"A"的原因了:)

答案 1 :(得分:1)

错误表明您的代码有什么问题。多字符字符常量表示您正在尝试将多个字符分配给错误的字符常量。正如mahendiran.b指出的那样,你不能指定&#34; A - &#34;或&#34; B - &#34;分级,因为它只需要一个字符。它应该是一个字符串。