首页 > 解决方案 > 程序打印 0 作为通过 scanf("%f") 获得的两个正整数相乘的结果

问题描述

我的代码:

#include <stdio.h>

int main()
{
    int l, b, a;
    printf("Enter the length of the rectangle: ");
    scanf("%f", &l);

    printf("Enter the breadth of the rectangle: ");
    scanf("%f", &b);

    printf("Area of rectangle is %f", l * b);
    return 0;
}

当我提供任何输入时,它不会向我显示它的产品,0.000000而是:

当我输入 2 和 3 时,它应该打印Area of rectangle is 6

标签: cscanf

解决方案


%f期望其对应的参数具有类型float并且您正在传递int给它,因此将其更改为%d将解决问题,因为%d期望其对应的参数具有 int 类型。

#include <stdio.h>
 
int main() {
   int length, breadth, area;
 
   printf("\nEnter the Length of Rectangle: ");
   scanf("%d", &length);
 
   printf("\nEnter the Breadth of Rectangle: ");
   scanf("%d", &breadth);
 
   area = length * breadth;
   printf("\nArea of Rectangle: %d\n", area);
 
   return 0;
}

推荐阅读