gpt4 book ai didi

c - C上的浮点异常,无法解决

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

我写了一个非常简单的代码,当我编译时(我告诉它当我输入 END 时,无论什么情况它都会破坏那个程序。)但是有消息显示“浮点异常:8”,我从来没有看到这个之前的消息,我一直在搜索谷歌,它告诉我我有一些事情发生在浮点值上,允许程序做它不应该做的事情。

/* Program: Taxi Day    
*
* Description: Calculate fartest taxi distance.
*
* Creator: Thunpisit Amnuaikiatloet #57070503418
*
* Create on: November. 26, 2014 17.55.00
*
* Lastest modify on: November. 26, 2014 17.55.00
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main()
{
char buffer[128];
char END[8] = ("END");
char MAXNAME[128];
int MAXRANGE = 0;
char taxiNumber[32];
int taxiStart = 0;
int taxiEnd = 0;
int taxiTotal = 0;
int taxiCount = 0;

while(1)
{
/* Ask user to enter Taxi Number */
printf("\nENTER TAXI NUMBER: ");
fgets(buffer,sizeof(buffer),stdin);
sscanf(buffer,"%s",taxiNumber);

/* If Taxi Number entered is END, stop asking */
if(strcasecmp(taxiNumber,END) == 0)
{
break;
}

/* Check Taxi Number validate */
while(strlen(taxiNumber) > 10)
{
printf("ENTER TAXI NUMBER: ");
fgets(buffer,sizeof(buffer),stdin);
sscanf(buffer,"%s",taxiNumber);
}

/* Ask user to enter start km */
printf("ENTER START KM?: ");
fgets(buffer,sizeof(buffer),stdin);
sscanf(buffer,"%d",&taxiStart);

/* Check Taxi Start validate */
while(taxiStart < 0)
{
printf("ENTER START KM?: ");
fgets(buffer,sizeof(buffer),stdin);
sscanf(buffer,"%d",&taxiStart);
}

/* Ask user to enter end km */
printf("ENTER END KM?: ");
fgets(buffer,sizeof(buffer),stdin);
sscanf(buffer,"%d",&taxiEnd);

/* Check Taxi Start validate */
while(taxiStart > taxiEnd)
{
printf("ENTER END KM?: ");
fgets(buffer,sizeof(buffer),stdin);
sscanf(buffer,"%d",&taxiEnd);
}

/* Calculate total distance for each taxi */
taxiTotal = taxiEnd - taxiStart;
printf("----------------------------------");

/* Show taxi entered information */
printf("\nTAXI %s HAS TRAVELED %d KM\n",taxiNumber,taxiTotal);

/* Compute the taxi that have largest distance */
if(MAXRANGE < taxiTotal)
{
MAXRANGE = taxiTotal;
strcpy(MAXNAME,taxiNumber);
}

/* Count number of taxi entered */
taxiCount++;
}

/* Print Summary */
printf("\nTAXI %s DROVE THE LONGEST RANGE, WHICH IS %d KM",MAXNAME,MAXRANGE);
printf("THERE ARE %d TAXIS TODAY, AVERAGE RANGE ARE %d KM",taxiCount,taxiTotal/taxiCount);
}

最佳答案

这可能是因为 taxiTotal/taxiCount 执行除以零 - 这会导致错误(表现为浮点异常,即使您只使用整数)。

这意味着 taxiCount 为 0,因此您可能更愿意这样做

if (taxiCount > 0) {
printf("THERE ARE %d TAXIS TODAY, AVERAGE RANGE ARE %d KM",taxiCount,taxiTotal/taxiCount);
} else {
puts("THERE ARE NO TAXIS TODAY");
}

关于c - C上的浮点异常,无法解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27148396/

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