Celeste
Celeste

Reputation: 33

C beginner, code not outputting properly

So I am very new to coding and this is the first time I have used scanf and printf to this extent. For my homework assignment we are supposed to create a program that calculates fuel efficiency in mpg and liters per 100km. The final answer is only supposed to have 2 decimal points... but that is another story. ;P

Right now, the program lets me enter a value for the first part (how many miles), however, once I click enter it skips to the end of my code and spews out a (seemingly) random number?

#include <stdio.h> /* tells computer where to find definitions for printf and scanf */
#define KMS_PER_MILE 1.61 /* conversion constant for miles to kms */
#define LIT_PER_GAL 3.79 /* conversion constant for gallons to liters */

int main(void)
{
    double miles, /* input - distance in miles. */
    gallons, /* input - gallons consumed */
    mpg, /* output - miles per gallon */
    kms, /* output - kilometers */
    liters, /* output - liters */
    lpkm; /* output - liters per 100 kms */

    /* get the distance in miles */
    printf("Enter the distance in miles> ");
    scanf("%1f", &miles);

    /* get the gallons consumed */
    printf("Enter the gallons consumed> ");
    scanf("%1f", &gallons);

    /* convert to mpg */
    mpg = (double)miles / (double)gallons;

    /* convert to lpkm */
    liters = LIT_PER_GAL * gallons;
    kms = KMS_PER_MILE * miles;
    lpkm = (double)liters / (double)kms * 100;

    /* Display fuel efficiency in mpg and lpkm */
    printf("The car's fuel efficiency is\n %1f mpg \n %1f liters per 100 kms", mpg, lpkm);
    return (0);

}

Upvotes: 0

Views: 1223

Answers (3)

user4039781
user4039781

Reputation:

For Printing you can use 1f but during taking input you must use lf .

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227418

Since you claim to be learning C++, if you had used the C++ standard library you would have avoided the problem:

#include <iostream> // std::cin, std::cout

int main()
{
  std::cout << "Enter the distance in miles> ";
  std::cin >> miles;
  std::cout << "Enter the gallons consumed> "
  std::cin >> gallons;
  ....

  std::cout << "The car's fuel efficiency is\n" << mpg << "\n" 
            <<  lpkm << " per 100 kms\n";
}

Upvotes: 2

VolAnd
VolAnd

Reputation: 6407

Try to change %1f to %lf in scanf.

For more details look C++ reference

Upvotes: 8

Related Questions