Programming issues. Writing a tax calculator: part 2.
Posted in Internet & technology on August 16th, 2007 by atma – Be the first to commentAfter playing around with the tax calculator I managed to write the zero or negative number control inside the method as I wanted before. It may seem too easy for expert programmers but for me was a bit tricky. First I used the while loop keyword and saw the printf line printing itself on the screen inside an infinite loop! Then I woke up and used the if/else statements.
The next problem was stopping the program from printing the lines that were at the main() function. The print method call, was printing 0′s anyway. So another if/else control on the print method was enough. I did change the print method, at the header file, in order to make it accept a single argument. I’m not sure if it was necessary for print to work as I wanted. Stop! Let’s test it! No! Here is the error: ‘p’ undeclared (first use in this function) which is quite normal, because the method doesn’t expect any variable or argument. However, I could try to declare the variable inside the method, but when I did that and try to compile the program, xcode crashed! Yeah! Am I good or what? Anyway, declaring inside a method a value that should be retrieved from outside doesn’t make much sense anyway.
So here is the code:
The .h file:
#import #import @interface TAX: Object { double price; } -(void) setPrice: (int) p; -(void) print: (int) p; @end
and the .m file:
#import #import #import "ivacalc.h" @implementation TAX -(void) print: (int) p { price = p; if ( p < 0 ) { printf("The price is %.2f and the tax is %.2f.\nThe sum is %.2f\n", price, price * 0.19, price + (price*0.19)); } else { printf("exiting\n"); } } -(void) setPrice: (int) p { if (p < 1) // don't do calculation for negative numbers { printf("The price is 0 or negative!\n"); p = 0; } else p = price; } @end int main(int argc, char *argv[]) { int j; TAX *myTax = [[TAX alloc] init]; // allocating and initializing a TAX-fellow class! printf("Price: "); scanf("%i", &j); printf("\n"); [myTax setPrice: j]; [myTax print: j]; [myTax free]; return 0; }
Now the program does check if the number entered is 0 or negative and prints an error message if it is.
