gpt4 book ai didi

C代码: What am I doing wrong?

转载 作者:行者123 更新时间:2023-11-30 18:53:34 28 4
gpt4 key购买 nike

我编写此代码是为了获取学生的字母成绩并计算他们的 GPA。当我运行该程序时,我可以正确获取学生的姓名和科目,但无法显示成绩或 GPA。

示例输入:

Sally
1
A
N

示例输出:

Enter Student Name: Sally
How many subjects: 1
Grades for subject 1: A
Student Name: Sally
Grade: 4.00
Do you want to enter another student? N

这是我尝试过的代码片段。

#include <stdio.h>

int main()
{
char studentName[20];
char grade[10];
int k1;
int totalSub1,totalGrade;
float gpa1;
char ch1;
do
{
//Student Name
scanf("%s",studentName);
printf("Enter Student Name: %s\n", studentName);

//Number of subjects
scanf("%d",&totalSub1);
printf("How many subjects: %d\n",totalSub1);

//Get Grades
for(k1=0;k1<totalSub1;k1++)
{
printf("Grades:\n%c",grade[k1]);
scanf("%c",&grade[k1]);
}
//Find the gade points
for(k1=0;k1<totalSub1;k1++)
{
totalGrade=0;
switch(grade[k1])
{
case 'A':
totalGrade+=4;
break;
case 'B':
totalGrade+=3;
break;
case 'C':
totalGrade+=2;
break;
case 'D':
totalGrade+=1;
break;
case 'F':
totalGrade+=0;
break;
}
}
//Calculate GPA
gpa1=totalGrade/totalSub1;
//Print Student name with GPA
printf("Student Name: %s\n",studentName);
printf("Grade: %.2f\n",gpa1);
printf("Do you want to enter another student?\n");
scanf("%c",&ch1);
}while(ch1=='Y'||ch1=='y');
getchar();
return 0;
}

最佳答案

您的代码中有两个问题:

   scanf("%c",&grade[k1]); 
scanf("%c",&ch1);

应替换为,

   scanf(" %c",&grade[k1]); //notice the whitespace
scanf(" %c",&ch1);

这告诉 scanf 忽略空格!了解它 here

此外,计算 GPA 的代码应替换为:

   gpa1=totalGrade/(float)totalSub1; 

假设一个人的 GPA 为 2.67,如果您不添加( float )字段 gpa1 将存储 2.00!

关于C代码: What am I doing wrong?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32678212/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com