gpt4 book ai didi

c - 为什么我的程序会跳过 switch 指令?

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

我正在尝试编写一个程序,在用户输入 7 个 float 之后;它们被存储到一个数组中,然后像这样打印出来:

日值直方图
1 37.8 ***
2 40.6 *****

其中 Istogram 列中 * 的数量由 value - 34 给出。

我写了这段代码:

#include <stdio.h>
#define OBSERVATION 7
#define MEDIAN 34

int main() {
float temp[OBSERVATION] = {0};

printf("Insert the patient's temperature over the course of 7 days: ");
for(int i = 1; i <= OBSERVATION; i++){
scanf("%f", &temp[i]);
}

printf("DAY\tVALUE\tISTOGRAM\n");
for(int i = 1; i <= OBSERVATION; i++){
printf("%6d\t%6g\n", i, temp[i]);
}
for(int i = 1; i <= OBSERVATION; i++){
switch ((int)temp[i] - MEDIAN) {
case 0: break;
case 1: printf("\t\t\t\t*");
break;
case 2: printf("\t\t\t\t**");
break;
case 3: printf("\t\t\t\t***");
break;
case 4: printf("\t\t\t\t****");
break;
case 5: printf("\t\t\t\t*****");
break;
case 6: printf("\t\t\t\t******");
break;
case 7: printf("\t\t\t\t*******");
break;
case 8: printf("\t\t\t\t********");
break;
case 9: printf("\t\t\t\t*********");
break;
case 10: printf("\t\t\t\t*********");
break;
case 11: printf("\t\t\t\t**********");
break;
case 12: printf("\t\t\t\t***********");
break;
}
printf("\n");
}

return 0;
}

代码编译良好并正确输出前两列,但完全跳过 switch 语句。我已经尝试检查当它被转换为 int 时是否错误地将 0 分配给 temp[i],但事实并非如此。不要那样做。它只是跳过开关

您还有更“紧凑”的方式来打印 * 列而不使用 switch 吗?

最佳答案

我会像这样重写你的代码:

#include <stdio.h>
#include "math.h"
#define OBSERVATION 7
#define MEDIAN 34

int main() {
float temp[OBSERVATION] = {0};
int iDifference = 0;

printf("Insert the patient's temperature over the course of 7 days: \n");
for(int i = 0; i < OBSERVATION; i++){
scanf("%f", &temp[i]);
}

然后打印标题:

  printf("DAY\tVALUE\tISTOGRAM\n");

开始行循环:

  for(int i = 0; i < OBSERVATION; i++){
// calculate the difference integer
iDifference = round(temp[i] - MEDIAN);
// don't add stars if the temperature diff is lower than 0
if(iDifference < 0) iDifference = 0;
// print the first two columns, notice that the new line isn't added yet
printf("%6d\t%6.2f\t", i, temp[i]);
// print the stars
vDrawStars(iDifference);
// then write the newline character
printf("\n");
}

return 0;
}

然后画星星例程:

void vDrawStars(int prm_iCount){
int p = 0;
// I didn't understand the case for it but
// printf("\t\t\t\t");
// then draw the needed stars
for(p = 0; p < prm_iCount; p++)
{
printf("*");
}
// no new lines, still on the same line.
}

这里有一个演示:https://onlinegdb.com/BJPyvDJRX

关于c - 为什么我的程序会跳过 switch 指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53365773/

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