doubles variable

This is a discussion on doubles variable within the C Programming forums, part of the General Programming Boards category; Hi. This is my first post, sorry if i seem a bit n00b. I just started learning C and I ...

  1. #1
    Registered User
    Join Date
    Jul 2007
    Posts
    8

    doubles variable

    Hi. This is my first post, sorry if i seem a bit n00b.

    I just started learning C and I met a problem.

    Code:
    #include <stdio.h>
    
    double oper;
    double a, b;
    double add, minus, divide, times;
    
    main()
    {
     printf("Please choose an operator. 1 for addition, 2 for subtraction, 3 
    
    for division and 4 for multiplication: \n");
     scanf("%d", &oper);
     printf("Enter the first number: \n");
     scanf("%
    d", &a);
     printf("Enter the second number: \n");
     scanf("%d", &b);
     add = b + a;
     minus = a - b;
     times = a * b;
     divide = a / b;
     if (oper == 1) {
      printf("%d + %d = %d", a, b, add);
     }
     if (oper == 2) {
      printf("%d - %d = %d", a, b, minus);
     }
     if (oper == 3) {
      printf("%d / %d = %d", a, b, divide);
     }
     if (oper == 4) {
      printf("%d * %d = %d", a, b, times);
     }
     getchar();
     return 0;
    }
    Yeah. When i run this, none of the operators work. For example, while adding stuff and i type 1, 2 and then 3 i get 2 + 0 = 3.

    But when I change the variables to int it all works again, just that it rounds off.

    How can I solve this problem?

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,211
    Stop reading and printing the variables as ints.

    Use &#37;f or %lf (search which is appropriate for scanf() and printf()... I think they are different.), but definitely not %d.

  3. #3
    Registered User
    Join Date
    Jul 2007
    Posts
    8
    thanks alot MacGyver!

  4. #4
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,211
    Welcome to cboard.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question about printing a variable???
    By Hoser83 in forum C++ Programming
    Replies: 2
    Last Post: 03-31-2006, 01:57 PM
  2. How accurate is the following...
    By emeyer in forum C Programming
    Replies: 22
    Last Post: 12-07-2005, 12:07 PM
  3. Replies: 2
    Last Post: 04-12-2004, 02:37 AM
  4. write Variable and open Variable and get Information
    By cyberbjorn in forum C++ Programming
    Replies: 2
    Last Post: 04-09-2004, 02:30 AM
  5. Variable question I can't find answer to
    By joelmon in forum C++ Programming
    Replies: 3
    Last Post: 02-12-2002, 04:11 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21