如何在C中的文本中舍入浮点数?

时间:2016-10-29 08:20:26

标签: c

所以我有这个文本

  

今天,西方国家人的平均寿命接近并超过80年   1日本82.6 123 19
  2香港82.2 234 411
  3冰岛81.8 345 26
  4瑞士81.7 456 7
  5澳大利亚81.2 567 500
  ...
  80立陶宛73.0 800 2
  ...
  194斯威士兰39.6 142 212
  195 133714 18.0 133 998
  196 100110011 10.0 667 87351

我需要将本文中的浮点数舍入为整数。我搜索了很多论坛,但我似乎无法找到我需要的东西。 此文本在.txt文件中给出。我的任务:"将实数(包含小数)舍入为整数。更正的文本应该是一个新的.txt"就是这样。

3 个答案:

答案 0 :(得分:3)

scanfsscanf是您提取字符串内容的最好朋友 floor使用full来压缩浮点数上的小数。然后可以用来围绕它(使用它包括math.h)...

格式字符串描述了预期的格式。函数返回找到的参数数量。

样品:

  • 初始化

    int id = -1;
    char country[160]; /* /!\ Warning country name length shall be fewer than 160 */
                       /*      Scanf don't care of this array parameter length. If it is too short */
                       /*      It will erase following memory...                 */
                       /* That is why scanf are often disparaging                   */
    float percent = 0.0;
    char a_number_as_string[10];
    int other_number = -1;
    char* Switzerland = "4 Switzerland 81.7654321 456 7";
    
  • 有效代码

     int ret = sscanf(Switzerland, "%d %s %f %s %d", &id, country, 
                      &percent, a_number_as_string, &other_number);
     if(ret == 5) {
         printf("~~ id: %d\n\tcountry: %s\n\tpercent: %.2f\n\tand    : "
                "(%s, %d)\n", id, country, percent, a_number_as_string,
                other_number);
    
         /////// ROUND
         printf("*** round");
         printf("\twith printf %%.1f = %.1f\n", percent);
         printf("\twith printf %%.2f = %.2f\n", percent);
         printf("\twith printf %%.3f = %.3f\n", percent);
         printf("\twith printf %%.4f = %.4f\n", percent);
    
         printf("*** With floor (included in math.h)\n");
         printf("\t1 decimal: %f\n", floor(percent*10)/10);
         printf("\t2 decimal: %f\n", floor(percent*100)/100);
         printf("\t3 decimal: %f\n", floor(percent*1000)/1000);
         printf("\t4 decimal: %f\n", floor(percent*10000)/10000);
     } else {
         printf("--> ret = %d", ret);
     }
    
  • 输出

      

    ~~ id:4

         
        

    国家:瑞士
        百分比:81.70
        和:(456,7)

      
         

    ***轮

         
        

    with printf%.1f = 81.8
        与printf%.2f = 81.77
        with printf%.3f = 81.765
        与printf%.4f = 81.7654

      
         

    ***楼层(包含在math.h中)

         
        

    1十进制:81.700000
        2位小数:81.760000
        3位小数:81.765000
        4十进制:81.765400

      

此功能在Unix,OSX,Unix终端手册页中描述:

  • man scanf
  • man sscanf
  • man floor

或者您可以在网上管理的多个副本中找到它,例如

答案 1 :(得分:1)

这是我已经测试过一行输入字符串的程序: -

// LINK - http://stackoverflow.com/questions/40317323/how-to-extract-float-numbers-from-text-in-c#40317323

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
int main()
{
    char s[100];
    int i,j;
    double sum=0.0,frac=0.0;
    gets(s); // delimited by '\n' and not by ' '
    for( i=0;s[i]!='\0';i++) // for finding index value of decimal point(.)
    {     
        if(s[i]=='.')
            break;
    }

    for(;s[i]!=' ';i--); // for changing key index value to the index value of the first space character(' ') before the decimal point(.)
    i++;

    for(i;s[i]!='.';i++)
    {
        sum=sum*10+(s[i]-48); // For extracting integer part
    }

    i++;
    for(i,j=1;s[i]!=' ';i++,j++)
    {
        frac=frac+(s[i]-48)/pow(10,j); // For extracting fractional part
    }
    printf("\n\n%lf",sum+frac); // final answer integer part+decimal part
    return 0;
}
说明: -

好的,所以我做的是: -
因为scanf()是由空间自动分隔的,所以我使用了gets(),它由新行分隔;
然后我们知道字符串中的浮点数会有一个小数点(。),所以我们找到数组中小数点的索引值(比如键)。
一旦我们找到了小数点,我们知道国家名后面只有小数点和空格字符之间的数字,所以现在我们找到该空格(键)的索引值。
现在从该键值开始,我们在计算整数部分时再次移动到小数点(。)字符索引。使用ASCII值计算,即字符的零值零(0)为48,字符Nine(9)为57因此从每个字符中减去48并提取该值。
再次从小数点(。)到字符串中的下一个空格字符是浮点数的一部分,小数点后的数字跟随权重10 ^( - 1),10 ^( - 2),10 ^( -3)......等等因此临时变量和power()函数。因此我们也成功地计算了小数部分。
最后,我刚刚在printf()中添加了Integer和小数部分。

尝试使用printf()包含每个for循环中的所有变量以便更好地理解,有点像干运行。

答案 2 :(得分:0)

您可以使用c#

中的regex解析字符串中的所有值
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] input = {
                "today average human lifespan in Western countries is approaching and exceeding 80 years.",
                "1 Japan 82.6 123 19",
                "2 Hong Kong 82.2 234 411",
                "3 Iceland 81.8 345 26",
                "4 Switzerland 81.7 456 7",
                "5 Australia 81.2 567 500",
                "80 Lithuania 73.0 800 2",
                "194 Swaziland 39.6 142 212",
                "195 133714 18.0 133 998",
                "196 100110011 10.0 667 87351"
                             };
            string pattern = @"(?'index'\d+)\s+(?'country'.*)\s+(?'float'[^ ]+)\s+(?'num1'\d+)\s+(?'num2'\d+)$";
            for (int i = 1; i < input.Length; i++)
            {
                Match match = Regex.Match(input[i], pattern);
                Console.WriteLine("index : '{0}', country : '{1}', float : '{2}', num1 : '{3}', num2 : '{4}'",
                    match.Groups["index"],
                    match.Groups["country"],
                    match.Groups["float"],
                    match.Groups["num1"],
                    match.Groups["num2"]
                    );
            }
            Console.ReadLine();
        }
    }
}
相关问题