从char *转换为int会失去精度 [英] Cast from char * to int loses precision

查看:325
本文介绍了从char *转换为int会失去精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从文件中读取数字。当我尝试将每个数字放入二维数组中时,出现以下错误。如何消除此消息?
我的变量:
FILE * fp;
char line [80];

I am reading numbers from a file.When I try to put each number into an double dimensional array it gives me below error.How do I get rid of this message? My variables: FILE *fp; char line[80];

错误:从char *转换为int会失去精度

代码:-

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

int main()
{
        FILE *fp;
        char line[80],*pch;
        int points[1000][10];
        int centroid[1000][10];
        float distance[1000][10];
        int noofpts=0,noofvar=0,noofcentroids=0;
        int i=0,j=0,k;

        fp=fopen("kmeans.dat","r");
        while(fgets(line,80,fp)!=NULL)
        {
                j=0;
                pch=strtok(line,",");
                while(pch!=NULL)
                {
                        points[i][j]=(int)pch;
                        pch=strtok(NULL,",");
                        noofvar++;
                        j++;
                }
                noofpts++;
                i++;
        }
        noofvar=noofvar/noofpts;
        printf("No of points-%d\n",noofpts);
        printf("No of variables-%d\n",noofvar);

        return 0;
}


推荐答案

这是有问题的行:

points[i][j]=(int)pch;

您应该将其替换为

points[i][j]=atoi(pch);

atoi 是一个函数,它将代表十进制表示形式的整数的C字符串转换为 int

这篇关于从char *转换为int会失去精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆