【发布时间】:2015-02-15 23:13:50
【问题描述】:
是的,我有 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 循环中直到文件末尾。
输入(距离文件): Line 1: 4 ,(时间文件) Line 1: 1 。 预期速度输出:0.25 实际输出:0.00
编辑:我的编码技能是 RIP 编辑2:错误,假设整数/整数会自动计算浮点值。我已经相应地更改了代码,它可以工作。谢谢各位。
【问题讨论】:
-
atoi 返回一个整数。设计 int/int 给出一个整数。您可以将第一个乘以 1.0,这会将其转换为浮点数,返回值将是浮点数
-
我可以推荐使用
double而不是float。 -
@ShaZiv “将第一个乘以 1.0 将其转换为浮点数”更好地表述为“将第一个乘以 1.0 将其转换为双精度”。要获得
float,请使用1.0f。
标签: c file loops structure scanf