Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

question about my program

Status
Not open for further replies.

amb669

Programmer
May 30, 2011
1
CA
hello everyone, i'm starting to learn the C language and was looking for some help from someone more experianced, anyway heres my program code and my problem.
this is kinda for a quiz, although i don't have to do the work myself i must know of an alternative to fix this bug other then the one provided

#include <stdio.h>

int main()
{
float a;
a = 0;
while (a <= 100)
{
if (a > 98.6)
{
printf("%6.2f degrees F = %6.2f degrees C\n", 98.6, (98.6 - 32) * 5.0 / 9.0);
}
printf("%6.2f degrees F = %6.2f degrees C\n", a, (a - 32.0) * 5.0 / 9.0);
a = a + 10;
}
return 0;
}


heres what it says "This program works if the ending value is 100, but if you change the ending value to 200 you will find that the program has a bug. It prints the line for 98.6 degrees too many times. We can fix that problem in several different ways. Here is one way:"


#include <stdio.h>

int main()
{
float a, b;
a = 0;
b = -1;
while (a <= 100)
{
if ((a > 98.6) && (b < 98.6))
{
printf("%6.2f degrees F = %6.2f degrees C\n", 98.6, (98.6 - 32.0) * 5.0 / 9.0);
}
printf("%6.2f degrees F = %6.2f degrees C\n", a, (a - 32.0) * 5.0 / 9.0);
b = a;
a = a + 10;
}
return 0;
}

if anyone knows any other ways other then the example provided to fix this bug it would be very very apppreciated.

thanks
Dustin
 
No "bugs" in the original program. There is a senseless printing of constant value(s) on every loop in the while statement.

Print the values of 98.6 and Cel(98.6) outside the loop and never invent such artificial constructs as in the 2nd case ;)
 
Sorry, if you want to print Cel(98.6) between 90 and 100, the 2nd snippet prints it, but try to rewrite the code, for example:
Code:
void print(double x)
{
  printf("%6.2f degrees F = %6.2f degrees C\n", x, (x - 32.0) * 5.0 / 9.0);
}

int main(void)
{
  double x, prev;
  double y = 98.6;
  double step = 10;
  double last = 100;

  for (x = prev = 0; x <= last; x += step) {
    if (prev < y && y < x)
       print(y);
    print(x);
  }
  return 0;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top