Hey a little stuck with prob a simple program :)

+2 Alec Sheen · November 12, 2015
Hey all wonder if you can help me am totally new to C so am trying out new things but this code is giving me funny results. Any help would be lovely :) thanks.

// The input should be 500
// the output should be 0.5
// the result this gives is 2686737


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

int main()

{
 double watt;
 double end = watt/1000;
 
 scanf("%d", &watt);
 printf("%d", &end);

return 0;
}

Post a Reply

Replies

Oldest  Newest  Rating
+1 Rian F · November 12, 2015
There's a few issues with your code. 

  • Firstly the "%d" in scanf and printf. "%d" is used for reading in and out putting  integer values.

  •  Secondly the printf statement is outputting an address because of the &. When out putting in values in C, there is no need to use the & symbol. I've code included below that fixes these isssues and more that I could find. 



#include
#include

int main()

{
//change to float for ease of reading and printing out
float watt, end;

scanf("%f", &watt);
end = watt/1000.00;
printf("%f", end); //notice no & operator

return 0;
}
0 Akhilesh Chobey · November 12, 2015
Hey, I just changed the position of the operation that you intend to perform and I think I got it. Anyone can please help me out here to understand why it works this way. 
Here's my code:

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

int main()

{
float watt;
float end ;

scanf("%f", &watt);
end = watt/1000;
printf("%f", end);
system("pause");
return 0;
}
0 Alec Sheen · November 12, 2015
Hi there Rian, thanks lots for explaining what i did wrong each item i watch Buckys video instead of moving onto the next i like to test and play around thinking of a little program i could make. So last night i did play around and made a watt cost calculator which works fine.

I notice though i still used the & operators and it works ? but i have seen others before with code and they say take out the & it's doing nothing for you but here is my messy code :). I am brand new though remember so there is prob better ways to make spaces in C but yea that's my way for now haha, again thanks for that code i will play around with it make sure i get the outputs i want.

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


int main()
{
 float watt, cost, hours, pause;

 printf("Enter the watts of your product.\n");
 scanf("%f", &watt);
 printf("\n");
 printf("Enter the cost of your electricity.\n");
 scanf("%f", &cost);
 printf("\n");
 printf("Enter the hours the product will be turned on.\n");
 scanf("%f", &hours);
 printf("\n");
 printf("\nThe cost of your appliance is, $%.2f", (watt/1000)*cost*hours/100);
 printf("\n");
 printf("\n");
 printf("\n");
 printf("Press any number or letter and hit enter to exit.");
 printf("\n");
 scanf("%s",&pause);




return 0;

}
  • 1

C

107,322 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator