0

This is the C program

#include <stdio.h>
#include <stdlib.h>

int main (void){

    double voltage, resistance;
    printf("Enter your Voltage: ");
    scanf("%f", &voltage);
    printf("Enter your Resistance: ");
    scanf("%f", &resistance);
    double amps = voltage / resistance;
    printf("With voltage %f and Ohm %fohms, amps is equal to %f \n", voltage, resistance, amps);
    return 0;
}

Why is voltage and resistance variables returning values of 0.00?

alk
  • 69,737
  • 10
  • 105
  • 255
Vbobo
  • 65
  • 1
  • 9
  • Hey thanks that worked, can you please explain what adding the 'l' does? – Vbobo Mar 20 '16 at 09:25
  • You might like to RTFM on `scanf()`: http://www.iso-9899.info/n1570.html#6.2.5p28 – alk Mar 20 '16 at 09:26
  • Your compiler should have warned on the mismatch between format-specifier and the type of argument passed. If not increase its warning level. Take warnings serious. – alk Mar 20 '16 at 09:29
  • OT: Your result string is missing units for voltage and current, as well as the input prompts do. The unit for resistance is not "ohms" but "Ohm", short Ω. – alk Mar 20 '16 at 09:31

2 Answers2

5

For scanf (and family) the format "%f" is for float, to get a double you need a "long" float which have the format-prefix l as in "%lf".


It should be noted that for printing floating point values with printf, all float arguments will be promoted to double. Which means that for printf there's no difference between %f and %lf.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

You should use %lf in your scanf.

This worked nice for me:

#include <stdio.h>
#include <stdlib.h>

int main (void){

double voltage, resistance;
printf("Enter your Voltage: ");
scanf("%lf", &voltage);
printf("Enter your Resistance: ");
scanf("%lf", &resistance);
double amps = voltage / resistance;
printf("With voltage %f and Ohm %fohms, amps is equal to %f \n", voltage, resistance, amps);
return 0;
}
George Bou
  • 568
  • 1
  • 8
  • 17