【问题标题】:Random numbers created when doing arithmetic's on float in c在 c 中对浮点数进行算术运算时创建的随机数
【发布时间】:2020-09-10 19:06:15
【问题描述】:

我对 c 很陌生,但我必须为学校创建一个程序,为此,我需要知道一个数字中有多少个十进制数,但是当我尝试这个时,一堆随机数来自第 4 维和我不知道如何解决它,有人可以帮助我吗?

代码如下:


int main(void) {
  float test = 1.567;
  while (test != 0){
    test = test * 10;  
    test = test - (int)test;
    printf("%f\n",test);
  }
}

编辑: 我在 Windows 10 上运行,我正在使用 repl.it 来编程和运行它。 这是我得到的输出

0.670000
0.700001
0.000008
0.000076
0.000763
0.007629
0.076294
0.762939
0.629395
0.293945
0.939453
0.394531
0.945312
0.453125
0.531250
0.312500
0.125000
0.250000
0.500000
0.000000

编辑 2: 任务是我们必须创建一个程序,您必须在其中输入金额,它会告诉您需要多少 2 欧元硬币、1 欧元硬币等。因为您不能有 4.63454 欧元我想确保您只能输入 2 个十进制数字,否则会引发错误。所以 TLDR:你通过键盘输入数字,但同样的事情发生了。

【问题讨论】:

  • 什么“一堆随机数”?你在什么操作系统上运行?你用的是什么编译器?
  • 在你的问题中显示你得到的输出。
  • 浮点变量不存储精确的小数位数。如果输入应该来自用户,那么我建议输入一个字符串并对其进行分析。
  • 标准 printf 格式 %f 仅打印 6 位数字。如果你使用例如printf("%.30f\n",test); 你会看到即使你的初始数字也没有确切的值。
  • @WeatherVane 如何对字符串进行计算?

标签: c math floating-point


【解决方案1】:

我想确保您只能输入 2 个十进制数字,否则会引发错误。

这确实是一个文本处理问题,因为"%f" 和朋友丢失了文本输入所需的小数位信息。

 char buf[100];
 if (fgets(buf, sizeof buf, stdin)) {
   char *endptr;
   double val = strtod(buf, &endptr);  // add errno check as desired 
   unsigned char *dp = strchr(buf, '.');
   if (endptr > buf && dp && isdigit(dp[1]) && isdigit(dp[2]) && dp[3] == '\n') {
      // success
      long long money = llround(val * 100.0);  // Scale by 100 and round to an integer
      ...
   } else {
      // error
   }
}

为了,考虑使用long long。十亿是not what it used to be

【讨论】:

    【解决方案2】:

    好的,我通过以下操作修复了它:

    #include <stdio.h>
    
    int main(void) {
      float test = 1.567;
      int euro = 0;
      int cent = 0;
      int eurocent = 0;
      float CentFloat = 0;
      euro = (int)test;
      CentFloat = test - euro;
      cent = CentFloat * 100;
      eurocent = euro *100 + cent;
      //test2 = test * 10;  
        
        printf("%.30f\n",test);
        printf("%d\n",euro);
        printf("%d\n",cent);
        printf("%d\n",eurocent);
      }
    

    这给出了以下输出:

    1.567000031471252441406250000000
    1
    56
    156
    

    这并不是我最初的想法,但它解决了必须检查是否有人输入了太多十进制数字的问题,并且使我的原始程序可以使用它并不难。谢谢大家的帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多