Hi, can someone give me an easy command that prevents a user from entering a negative value in the following code i made? thanks.

#include <iostream>

using namespace std;

int main()
{
   int X;
   int Y;
   cout<<"please enter the value of X and Y";
   cin>>X;
   cin>>Y;
   float result;
   result=4*X^3+Y^3-4;
   cout<<"the result of Z="<<result;
    return 0;
}

Recommended Answers

All 2 Replies

Sure. Initialize X and Y to say -1. Now put a while test for X and Y being negative around lines 9 to 11.

commented: im sorry what does that mean +0

Is there a specific reason you need to ensure that the values are positive?

As per RProffitt's suggestion, here is how you would loop on the input to require that the input value is positive.

#include <iostream>

using namespace std;

int main()
{
   int X = -1;
   int Y = -1;
   while (X < 0)
   {
       cout<<"please enter a positive value for X";
       cin>>X;
   }
   while (Y < 0)
   {
       cout<<"please enter a positive value for Y";
       cin>>Y;
   }
   float result;
   result=4*X^3+Y^3-4;
   cout<<"the result of Z="<<result;
   return 0;
}

A simpler alternative is to use abs() (which requires you to #include <cmath>) to force the value positive regardless of whether it was negative or not. However, looping on the input is advisable in any case, to hand the instance where the input is a string.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.