gpt4 book ai didi

c - 一个简单的程序有些奇怪,可能是 scanf 问题

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

我有一个简单的作业...制作一个需要 3 个值 3 次的 C 程序

  1. 食物的 ID(字符)
  2. 食物的热量值( float )
  3. 食物量( float )

这是程序给我的代码和输出:

#include <stdio.h>
#define NUM_OF_FOOD 3

int main()
{
float food_cal[NUM_OF_FOOD];
float food_amount[NUM_OF_FOOD];
char food_id[NUM_OF_FOOD];
int i;
float total_cal=0;
int most_fat_food_id=0;
printf("enter the following data: food ID, Cal value and Amount eaten \nexample A 10 3\n");
for (i=0;i<NUM_OF_FOOD;i++)
{
printf("\nEnter product #%d:",i);
int inputLength = scanf("%c %f %f",&food_id[i],&food_cal[i],&food_amount[i]);
if ( inputLength < 3 ) {
printf("input error, input length was %d excpexted 3", inputLength);
break;
}
if ( !((food_id[i]>96 && food_id[i]<123) || (food_id[i]>64 && food_id[i]<91)) ) {
printf("ID input error");
break;
}
if ( food_cal[i] < 0 ) {
printf("Food Cal input error");
break;
}
if ( food_amount[i] < 0 ) {
printf("Food Amount input error");
break;
}
printf("\n%c %5.2f %5.2f",food_id[i],food_cal[i],food_amount[i]);
}
for (i=0;i<NUM_OF_FOOD;i++)
total_cal+=food_cal[i]*food_amount[i];

printf ("\nTotal amount of calories is %5.2f\n",total_cal);
for (i=1;i<NUM_OF_FOOD;i++)
most_fat_food_id = (food_cal[most_fat_food_id]<food_cal[i]) ? i : most_fat_food_id;

printf ("\nThe most fattening product is: %c with %5.2f calories",food_id[most_fat_food_id],food_cal[most_fat_food_id]);

return 0;
}

/*
enter the following data: food ID, Cal value and Amount eaten
example A 10 3

Enter product #0:A 1000 2

A 1000.00 2.00
Enter product #1:B 500 3
input error, input length was 1 excpexted 3
Total amount of calories is 2000.00

The most fattening product is: A with 1000.00 calories
*/

它只是跳过第三个输入

不知道为什么...两个人看了代码,看起来不错,但仍然有错误。

最佳答案

输入:A 1000 2[ENTER]B 500 3[ENTER]...

第一个 scanf("%c %f %f") 读取“A”、1000 和 2,并在 [ENTER] 处停止

第二个 scanf("%c %f %f") 读取 [ENTER] 并用 B 进行“%f”转换。

您可以尝试使用 scanf("%c %f %f") 在读取字符之前强制跳过可选空格。

关于c - 一个简单的程序有些奇怪,可能是 scanf 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4128063/

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