gpt4 book ai didi

C - 打印函数返回的字符

转载 作者:行者123 更新时间:2023-11-30 19:11:10 25 4
gpt4 key购买 nike

更新:最后的 if 语句 if(lettergrade <= 'A' && lettergrade >= 'F')错误,因为 F (70) 的 ascii 值大于 A (65)。

我正在尝试打印 C 中函数返回的字符。

我的函数 allocateletter 被赋予一个 float ,并返回一个字符。

当我按原样运行程序时:

skirchbaum:~/workspace/HMWK/HMWK4 $ ./assignletter 
Enter pointsgrade
100
Pointsgrade: 100.00 Lettergrade:

没有打印任何字母等级(我尝试过多种情况 - 100.1、1 等)

我做错了什么?

代码:

/* Input: a grade as points
Functionality: converts point grade into letter grade
Output: a char representing the letter grade, or -1 if error

LETTER GRADE BREAKDOWN:
A = 100 - 91
B = 90 - 81
C = 80 - 71
D = 70 - 61
F = 60 and below
*/


#include <stdio.h>
#include <stdlib.h>
#define DEBUG 1

char assignletter(float pointsgrade);

char lettergrade;
float pointsgrade;

int main(){
//Input a pointsgrade for debugging
#ifdef DEBUG
printf("Enter pointsgrade\n");
scanf("%f", &pointsgrade);
lettergrade = assignletter(pointsgrade);
printf("Pointsgrade: %.2f Lettergrade: %c\n", pointsgrade, lettergrade);
#endif
}

char assignletter(float pointsgrade){

char lettergrade;

//Grade A
if(pointsgrade <= 100 && pointsgrade >= 91){
lettergrade = 'A';
}

//Grade B
if(pointsgrade <= 90 && pointsgrade >= 81){
lettergrade = 'B';
}

//Grade C
if(pointsgrade <= 80 && pointsgrade >= 71){
lettergrade = 'C';
}

//Grade D
if(pointsgrade <= 70 && pointsgrade >= 61){
lettergrade = 'D';
}

//Grade F
if(pointsgrade <= 60){
lettergrade = 'F';
}

//Return letter grade or -1 if error
if(lettergrade <= 'A' && lettergrade >= 'F'){
return lettergrade;
}
else{
return -1;
}
}

最佳答案

条件格式不正确,ASCII 中的“F”为 70 'A' 是 65 所以

if (lettergrade <= 'A' && lettergrade >= 'F') {
return lettergrade;
}

不会评估为 true,因为字母等级 ('A') 小于 70 ('F') 并且不大于它

你宁愿这样做

if (lettergrade >= 'A' && lettergrade <= 'F') {
return lettergrade;
}

通过翻转大于和小于符号

关于C - 打印函数返回的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40568891/

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