【问题标题】:Error in converting double to int将 double 转换为 int 时出错
【发布时间】:2024-01-10 07:52:01
【问题描述】:

我有一个有 2 个双精度值作为输入的代码,然后我想将其转换为 2 个整数。我认为这要么是取消引用的问题,要么是我的强制转换语法关闭。提前致谢

#include <stdio.h>

int main()
{
    double * int1;
    double * int2;

    printf("Put in two numbers:");
    scanf("%lf", int1);
    scanf("%lf", int2);

    int a = (int) (int1);
    int b = (int) (int2);

    printf("%d\n%d", a, b);
}

【问题讨论】:

    标签: c casting int double


    【解决方案1】:

    它仍然说错误:从指针转换为不同大小的整数

    您没有将“double 转换为 int”...您将“double* 转换为 int”。

    改变

    int a = (int) (int1);
    /*             ^^^^ this is a pointer */
    

    int a = (int) (*int1);
    /*             ^^^^^ this is a double */
    

    【讨论】:

      【解决方案2】:

      在我看来,您可以通过两种方式做到这一点,一种使用堆上的指针和动态内存,另一种使用自动值。

      动态分配内存的指针

      #include <stdio.h>
      #include <stdlib.h>
      int main()
      {
          double * int1 = malloc(sizeof(double));
          double * int2 = malloc(sizeof(double));
      
          printf("Put in two numbers:");
          scanf("%lf", int1);
          scanf("%lf", int2);
      
          int a = (int) *int1;
          int b = (int) *int2;
      
          printf("%d\n%d", a, b);
          free(int1);
          free(int2);
      }
      

      在系统堆栈上自动分配值

      #include <stdio.h>
      
      int main()
      {
          double int1;
          double int2;
      
          printf("Put in two numbers:");
          scanf("%lf", &int1);
          scanf("%lf", &int2);
      
          int a = (int) int1;
          int b = (int) int2;
      
          printf("%d\n%d", a, b);
      }
      

      注意:我在您的示例中使用指针的方式看到的一个问题是没有它们指向的内存,我相信 scanf 不会为指针分配内存。

      【讨论】:

        【解决方案3】:

        改变你的台词

        scanf("%lf", int1);
        scanf("%lf", int2);
        

        scanf("%lf", &int1);           //Use '&'
        scanf("%lf", &int2);
        

        不要为此使用指针变量。

        【讨论】:

        • 这仍然给了我错误:从指针转换为不同大小的整数 [-Werror=pointer-to-int-cast]
        【解决方案4】:

        你的程序应该是什么样子:

        #include <stdio.h>
        
        int main( void )
        {
            double value1;
            double value2;
        
            printf("Put in two numbers:");
            scanf("%lf", &value1);
            scanf("%lf", &value2);
        
            int a = value1;
            int b = value2;
        
            printf("a=%d b=%d\n", a, b);
        }
        

        传递给scanf 的参数需要是适当变量的地址。所以你需要声明变量,例如double value1 然后将该变量的地址传递给scanf,例如scanf(..., &amp;value1);

        C 语言支持将double 隐式转换为int,因此您根本不需要转换。隐式转换将截断数字。如果要将数字四舍五入到最接近的int,则需要使用round 函数。

        【讨论】: