שאלה 3
Back Up

 

/*
  Module: tr4_q3.cpp
  Author: Yariv Amar
  What? This program prints all the results of equations 
        type Ax+By+Cz=D in given range of numbers.
  
  Input : N - represent the range of x,y,z (-N/2<=x,y,z<=N/2)
  Output: The number of results
	      2 of results 
  Assumptions on input: Integer even number grater than 2
  How?
  Using 2 nesting loops for x and y and calculating .z according 
  to x&y. checking whether z is also in the range and counting 
  that result. We also store the first 2 results as an example of 
  correct x,y,z and print them at the end.
*/
#include <iostream.h>
void main()
{
	int x,y,z,N;
	int x1,y1,z1,x2,y2,z2; //defining temp variable
	int Counter=0;
	const int A=4;	//x prefix
	const int B=-18;//y prefix
	const int C=2;	//z prefix
	const int D=30;	//result
	cout<<"Please enter the range of results: ";
	cin>>N;
	
	for (x=(-N/2);x<=N/2;x++) //start loop on x
		for (y=(-N/2);y<=N/2;y++) //start loop on y
		{
			z=(D-A*x-B*y)/C; //calculate Z
			if (z>=(-N/2) && z<=N/2)  //check if z is in the range.
			{  
				Counter+=1;
				if (Counter<=2) //prevent checking if have 2 results
				if (Counter==1) //remember the 1st
				{
					x1=x ; y1=y ; z1=z;
				} 
				else //remember the 2nd
				{
					x2=x ; y2=y ; z2=z;
				}
			}	
		}//End loop on y
	//End loop on x
//print results
	cout<<"The number of results is: "<<Counter<<"\n";
	cout<<"x="<<x1<<" y="<<y1<<" z="<<z1<<"\n";
	cout<<"x="<<x2<<" y="<<y2<<" z="<<z2<<"\n";
}

פלטים מיצגים

 

Please enter the range of results: 10
There number of results is: 14
x=-5 y=-3 z=-2
x=-4 y=-3 z=-4

 

Please enter the range of results: 100
There number of results is: 1134
x=-50 y=-18 z=-47
x=-50 y=-17 z=-38

 

Please enter the range of results: 1000
There number of results is: 111334
x=-500 y=-168 z=-497
x=-500 y=-167 z=-488

 

© Copyright YAProductions 2000