gpt4 book ai didi

c - 在 C 中显示 float

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

是的,我有 2 个文件(距离和时间)在它们的行上有不同的值,在程序中将两个值在线划分为它们的速度并显示在屏幕上。

这很完美,但是,该函数将计算值提供给最接近的整数:

#include <stdio.h>


int main()
{

FILE *fTotDc;
FILE *fTotTc;

int CalScD; //Values for total cycling speed
int CalScT;
float CalScS;
char ScSValue[32];

int DataCount=1; //File line comparison

struct store06 //TICtotD
{
char defTotDc[16];
}stock06[512];


struct store08 //TICtotT
{
char defTotTc[16];
}stock08[512];

fTotDc=fopen("TICtotD.txt","r"); //Opens total distance
fscanf(fTotDc,"%16[^\n]%*.2f", stock06[DataCount].defTotDc);
fTotTc=fopen("TICtotT.txt","r"); //Opens total time
fscanf(fTotTc,"%16[^\n]%*.2f", stock08[DataCount].defTotTc);

printf("|Distance |Time |Speed |");
printf("\n");

printf("|%-16s", stock06[DataCount].defTotDc);
printf("|%-16s", stock08[DataCount].defTotTc);

CalScD = atoi(stock06[DataCount].defTotDc); //Totals are converted to int for calculation
CalScT = atoi(stock08[DataCount].defTotTc);

if(CalScT == 0) //Test for 1/0 error, There is also a failsafe in the edit function which checks for t=0;
{
if(CalScD == 0) //If distance is 0 (As it is by default), the speed is 0.
{
printf("|0 ");
}
else //If distance is not 0 , we have (1/0)*k, which doesn't exist.
{
printf("|Error, Time is 0");//Error message given.
}
}
else
{
CalScS = CalScD/CalScT;
snprintf(ScSValue,32,"%.2f", CalScS); //Turns this int value into a string
printf("|%-16s",ScSValue); //String outputted
}

printf("|"); //last column
getch();
}

这是一行代码,假设这是一个 do-while 循环,直到文件结束。

输入(距离文件):第 1 行:4,(时间文件)第 1 行:1。预期速度输出:0.25实际产出:0.00

编辑:我的编码技能是 RIP编辑 2:错误,假设整数/整数会自动计算浮点值。我已经相应地更改了代码,它有效。谢谢你们。

最佳答案

CalScS = CalScD/CalScT; 中,首先执行 integer 除法,然后将结果值转换为 float 并分配给变量。

试试这个

CalScS = CalScD/(double)CalScT;

先将分母转为 float ,再进行除法赋值。

哦......而且(几乎)总是喜欢 double 而不是 float

关于c - 在 C 中显示 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27525024/

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