Help with this code....

Started by
2 comments, last by ekawanishi 16 years, 2 months ago
Hi there I am new to these forums, hope you can help me. Here is what I have: [Edited by - ekawanishi on February 21, 2008 6:03:53 PM]
Advertisement
  • Width and precision specifiers are not valid in scanf conversion specifiers.

  • The scanf conversion specifier for a double is %lf, not %f.

  • It's redundant to assign zero to a variable just before assigning it a different value.

  • You have some common code that can be moved out of the if statements and put at the end of the loop.

  • You really ought to do some error checking

  • puts is superior to printf if all you're doing is printing a newline terminated string with no formatting.

  • This would be so much easier and less error-prone in C++!
#include <stdio.h> #include <math.h> int main(void) { 	double A=0, B=0, C=0, x=0, y=0; 	int i;	printfputs("Enter (double) A, B and C:\n"); 	if (scanf("%6.5lf %6.5lf %6.5lf", &A, &B, &C) != 3)	{		puts("Error - could not read three doubles from input");		return -1;	}	for(i=0;i< 4;i++) 	{ 		printfputs("Enter (double) x:\n"); 		if (scanf("%6.5lf", &x) != 1)		{			puts("Error - could not read double from input");			return -1;		}		if(x<=1) 		{ 			printfputs("Case 1\n"); 			y=0;			y=fabs(pow(x,3)); 			printf("x value is =%6.5f and y value is =%6.5f",x,y);		} 		else if(x>1 && x<=2) 		{ 			printfputs("Case 2\n"); 			y=0;			y=exp(0.5*x) - A; 			printf("x value is =%6.5f and y value is =%6.5f",x,y);		} 		else if(x>2 && x<=10) 		{ 			printfputs("Case 3\n"); 			y=0;			y=B*log10(x) - log(x); 			printf("x value is =&6.5f and y value is =%6.5f",x,y);		} 		else 		{ 			printfputs("Case 4\n"); 			y=0;			y=C*pow((x+1),-1.5); 			printf("x value is =%6.5f and y value is =%6.5f",x,y);		} 		printf("x value is =%6.5f and y value is =%6.5f\n",x,y);	} }
Σnigma
In code of the form

if (foo) {} else if (!foo && bar) {} else {}


, the '!foo' is entirely redundant.
Thanks for the tips guys. You have been of great help.

This topic is closed to new replies.

Advertisement