Why isnt this working? printf doesnt print variable inside a if block? Works outside?

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: Feb 2009
Posts: 8
Reputation: crewxp is an unknown quantity at this point 
Solved Threads: 0
crewxp crewxp is offline Offline
Newbie Poster

Why isnt this working? printf doesnt print variable inside a if block? Works outside?

 
0
  #1
Mar 5th, 2009
I have a small problem. I'm curious to see why this happens. If you run this code and enter the data, I put in a debug line. Inside the 'if (grade2>grade) block, the DEBUG printf's don't show the data correctly.

Outside the if block, I print pretty much the same line. It shows it correctly on that line.

Anyone know why? I'm learning a lot about c as I go. Thanks!
  1. int main(void)
  2. {
  3. char fi='a';
  4. char li='a';
  5. double grade=0;
  6. int z=0;
  7. int t=4;
  8. printf("Entered %d students in Class \n",t);
  9. for (z=0;z<t;z++)
  10. {
  11. printf("Enter student %d's data. Ex:BM100 (Bob Marley has a 100) :: ",(z+1));
  12. char fi2='a';
  13. char li2='a';
  14. double grade2=0;
  15. scanf("%c%c",&fi2,&li2);
  16. //printf("\n");
  17. scanf("%d",&grade2);
  18. getchar();
  19. if (grade2>grade)
  20. {
  21. grade=grade2;
  22. fi=fi2;
  23. li=li2;
  24. printf("DEBUG-CHANGE! ADDED %d BY '%c' '%c' as highest grade!\n",grade,fi,li);
  25. printf("DEBUG-CHANGE2! ADDED %d BY %c %c as highest grade!\n",grade2,fi2,li2);
  26. }
  27.  
  28. printf("DEBUG-STUDENT %d DATA:: NAME:%c%c GRADE:%d",z,fi2,li2,grade2);
  29. }
  30.  
  31. return 0;
  32.  
  33. }
Reply With Quote Quick reply to this message  
Join Date: Jan 2009
Posts: 46
Reputation: kbshibukumar is an unknown quantity at this point 
Solved Threads: 7
kbshibukumar kbshibukumar is offline Offline
Light Poster

Re: Why isnt this working? printf doesnt print variable inside a if block? Works outside?

 
0
  #2
Mar 5th, 2009
Why are you trying to read a double using "%d"? Use "%lf" instead.
scanf("%lf",&grade2);
Reply With Quote Quick reply to this message  
Join Date: Feb 2009
Posts: 8
Reputation: crewxp is an unknown quantity at this point 
Solved Threads: 0
crewxp crewxp is offline Offline
Newbie Poster

Re: Why isnt this working? printf doesnt print variable inside a if block? Works outside?

 
0
  #3
Mar 5th, 2009
thanks kbs. I looked at what you suggested and saw that I had mis-understood how C takes in datatypes. I fixed all the misrepresentations in my code and it works fine now.

Thanks
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Other Threads in the C++ Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC