Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

C Double type displays zeros after point

I have this weird problem. When I write a double type number, it gets stored in the

double data;

variable. Then when I compile and run the code the number gets printed out as for example 3697.0000 when I have written 3697.47595.

Here is the code:

#include <stdio.h>

const int n = 12;
int stack[n], top = -1;

double Read()
{
    int x = 0;
    if(top < 0)
        printf("Empty stack!");
    else
    {
        x = stack[top];
        top--;
    }
    return x;
}

void Write(int x)
{
    if(top == n-1)
        printf("The stack is full");
    else
    {
        top++;
        stack[top] = x;
    }
}

int main()
{
    double data;
    printf("Enter a double (0 for quit): ");
    scanf("%lf", &data);
    while(data > 0)
    {
        Write(data);
        printf("Enter a double (0 for quit): ");
        scanf("%lf", &data);
    }
    printf("---------------------------");
    printf("
The stack contains:
");
    while(top >= 0 )
        printf("%lf ", Read());

    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The value is truncated to int because the elements of the array stack, the argument of Write, and the variable x to temporarily store the value in Read are int. Use double for them to deal with double value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...