Need help with re-assigning variable values


#1

I have main that calls getVars and passes the values back to main. Them those values are passed to GetSqrt. However, if GetSqrt detects negative values, it calls GetVars itself. However, it is not correctly re-assigning the variable value for getSqrt to use. GetSqrt for some reason still has the first set of values passed from main in memory. What happened?


int getSqrt(int a, int b, int c, float*sqrt_a, float*sqrt_b, float*sqrt_c)
{
	/*comparison test to determine if negative numbers were inputted.
	if test passes, square roots of variables are taken and returned.
	else, the user is notified of the calculation error.*/
	do
	{
	     if(a >= 0 && b >= 0 && c >=0)
	     {
	          *sqrt_a=(float)sqrt(a);
	          *sqrt_b=(float)sqrt(b);
	          *sqrt_c=(float)sqrt(c);
	          break;
         }
         else
         {
              printf("
Sorry, this program cannot evaluate square roots for 'i.'");
              printf("
Please provide new inputs.
");
			  getVars(&a, &b, &c);
         }
    }while(a < 0 || b < 0 || c < 0);
	return 0;
}


#2

can you show getvars?


#3

sure:


int getVars(int*a, int*b, int*c)
{
    //local definitions
    int input_a;
    int input_b;
    int input_c;
    
	//prompts for user to assign values to variables
    printf("
Please enter 3 integers, each separated by a space: ");
	scanf("%d %d %d", &input_a, &input_b, &input_c);
    *a=input_a;
    *b=input_b;
    *c=input_c;
    return 0;
}


#4

your loop is your problem

you only do the loop while a<0 || b<0 || c<0. but after you call getvars, and the user enters positive values the loop isn’t exectuted anymore. so you aren’t calculating any sqrts.


	bool calculated = false;
	do
	{
	     if(a >= 0 && b >= 0 && c >=0)
	     {
	          *sqrt_a=(float)sqrt(a);
	          *sqrt_b=(float)sqrt(b);
	          *sqrt_c=(float)sqrt(c);
			  calculated = true;
         }
         else
         {
              printf("
Sorry, this program cannot evaluate square roots for 'i.'");
              printf("
Please provide new inputs.
");
			  getVars(&a, &b, &c);
         }
    }while(!calculated);


#5

oooh, gotcha. Thanks. i was trying to figure out what the heck was going on there. I knew it was something in the loop but couldn’t figure it out. Anyhow, I ended up rewriting the code to have getVars and getSqrt called in a do while loop with some if then statements directly in main instead of having getSqrt calling getVars in itself… ehr. Yeah. I hope I don’t get docked points for this… man, so burned out. 19 units was a bit too much this quarter.


#6

This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.