gpt4 book ai didi

c - 用户将 float 放入整型变量

转载 作者:太空宇宙 更新时间:2023-11-04 06:48:52 24 4
gpt4 key购买 nike

我在 Linux Ubuntu 上使用 gcc 编译器。这是我的问题:我很困惑为什么我的程序会这样做。当我放置一个 float 时,为什么它会跳过我剩余的 scanf 语句。我知道您不想将 float 放入整数中,但为什么要这样做。它不会砍掉小数点吗,为什么它会在变量中放入大数字。有人可以解释一下吗? P.S 我知道如何修复它,我只是想知道为什么会这样。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main() {
int i = 0;
int gamesPlayed = 0;
int goals[gamesPlayed];
int totalGoals = 0;
float avg = 0;

printf("How many games have you played? ");
scanf(" %d", &gamesPlayed);

for (i=0; i < gamesPlayed; i++)
{
printf("How many goals did you score in game %d? ", i+1);
scanf(" %d", &goals[i]);
totalGoals += goals[i];
printf("%d\n", totalGoals);
}

avg = ((float)totalGoals / gamesPlayed);
printf("Total Goals: %d\n", totalGoals);
printf("Avg: %.2f\n", avg);


return 0;
}

错误:
你玩过多少游戏? 2.62.000000

您在第一场比赛中进了多少球? 1863382920

你在第二场比赛中进了多少球? 1863415686

总进球数:1863415686

平均:931707840.00

最佳答案

对于输入 2.6,第一个 scanf 将读取 2 并在输入流中留下 .6

下一个 scanf 将看到无法转换为整数的 .。因此 scanf 返回并使 goals[i] 未初始化。输入流仍将包含 .6,因此在循环中一次又一次地发生完全相同的情况。

然后您使用未初始化的变量来计算平均值,因此您最终得到“奇怪”的值。注意:使用未初始化的变量是未定义的行为。

请注意,问题与 float 无关。问题很简单,输入包含一个无法转换为整数的字符。输入 2HelloWorld6 会得到相同的结果。

您需要检查 scanf 返回的值,例如:

if (scanf(" %d", &goals[i]) != 1)
{
// Ups - could not scan an integer

... add error handling here ...
}

顺便说一句:考虑使用 fgets 读取用户输入并使用 sscanf 进行扫描。在大多数情况下,它比使用 scanf 容易得多,因为您不会遇到某些字符卡在输入流中的情况。

关于c - 用户将 float 放入整型变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54308683/

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