如何解决C编程中的float带来的问题?

时间:2018-10-29 17:53:13

标签: function

当我编译c程序时,对于每种绘制,浮点数给我一个数字,而不是一串零。例如: 1.00000000 2.00000000 2.00000000。 当我实际输入尺寸20 40 9和门窗数量4和8时,实际上应该给我1.64 2.25和2.57。

要解决此问题,我需要在倒数第三个函数中进行哪些更改?

#include <stdio.h>
#include <stdlib.h>
#define AREA_OF_DOOR 21
#define AREA_OF_WINDOW 12
#define SQUARE_FEET_OF_SPLASH_OF_COLOR 550 
#define SQUARE_FEET_OF_CHANGING_THE_MOOD 400
#define SQUARE_FEET_OF_COVER_ALL_SINS 350

void display_room_dimension_user_prompt();
void display_doors_windows_user_prompt();
void display_gallons_needed(int length, int width, int height, int doors, int windows);

int main()
{
    int length; 
    int width;
    int height;
    int doors; 
    int windows;
    
    display_room_dimension_user_prompt();
    scanf("%d %d %d", &length, &width, &height);
    
    display_doors_windows_user_prompt();
    scanf("%d %d", &doors, &windows);
    
    display_gallons_needed(length, width, height, doors, windows);
    
    printf("\nProgram Terminated");
}

void display_room_dimension_user_prompt()
{ 
    int length, width, height;
    printf("Enter the the length, width, and height(in this order).");
    printf("\n(For example: 20 40 9)");
    printf("\n--> ");
    
}

void display_doors_windows_user_prompt()
{
    int doors, windows;
    printf("\nEnter the number of standard doors and windows (in this order).");
    printf("\n(For example: 4 8)");
    printf("\n--> ");        
}

void display_gallons_needed(int length, int width, int height, int doors, int windows)
{
    int SQFT = 2 * height * width + 2 * height * length - doors * AREA_OF_DOOR - windows * AREA_OF_WINDOW;
    float dec_splash_of_color, dec_changing_the_mood, dec_cover_all_sins;
    
    printf("\n%d feet long",length);
    printf("\n%d feet wide and", width);
    printf("\n%d feet high with", height);
    printf("\n%d standard doors and", doors);
    printf("\n%d standard windows", windows);
    
    printf("\nresults in %d sq.ft of wall to be covered.", SQFT);
    
    dec_splash_of_color = SQFT / SQUARE_FEET_OF_SPLASH_OF_COLOR;
    dec_changing_the_mood = SQFT / SQUARE_FEET_OF_CHANGING_THE_MOOD;
    dec_cover_all_sins = SQFT / SQUARE_FEET_OF_COVER_ALL_SINS;
    
    printf("\n%f gallons of 'splash-of-color' type paint or", dec_splash_of_color);
    printf("\n%f gallons of 'change-the-mood' type paint", dec_changing_the_mood);
    printf("\n%f gallons of 'cover- all- sins' type paint", dec_cover_all_sins);
    printf("\nare required to paint the room.");      
}

1 个答案:

答案 0 :(得分:0)

也许是您的类型,再结合您的输出方式...针对“色彩飞溅”,请尝试:

#define SQUARE_FEET_OF_SPLASH_OF_COLOR 550.0  //note the decimal 

...

float SQFT = 2 * height * width + 2 * height * length - doors * AREA_OF_DOOR - windows * AREA_OF_WINDOW;  //change to float

...

dec_splash_of_color = SQFT / SQUARE_FEET_OF_SPLASH_OF_COLOR;//leave as is

...

printf("\n%.2f gallons of 'splash-of-color' type paint or", dec_splash_of_color);//note the change in "%.2f" (2 decimals)