In C++, is there anyway to see if a number divided by another is a whole number or not, and have that number disregarded if it a decimal. For example, if I have a program that divides two user-inputted numbers, and the user puts in 2 and 3, have the program output: "The number is a decimal". But if they put 4 and 2, have the program output: "The quotient is 2".
If you can think it, then there is a way for it in C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
int main(){
int x,y; //for user input
int z; //for storing remainder
std::cin >> x >> y; //take inputs
z=x%y; //calculate remainder
if(z>0) //if remainder greater than zero
std::cout << "The number is a decimal"; //print message
else //otherwise
std::cout << "The quotient is " << x/y; //print message and answer
return 0;
}
If you are using just cout << "Hi!" << endl; rather than std::cout << "Hi!" << std::endl; then you must have a line somwhere above that says usingnamespace std;
The using directive tells the compiler to look in that namespace as well as the global namespace when looking for a symbol. That is, if you are "using namespace std", when it fails to find "cout" in the global namespace, it automatically tries "std::cout".
It is seen as better practice to avoid using directives at global scope as it avoids "cross-talk" between different namespaces. But it is not uncommon to use "using namespace std" for smaller bits of code.
I generally code with explicit std::s unless I'm doing a lot of (e.g.) string manipulation. But then I use the using directive within function scope, so only the relevant functions see the whole of standard namespace.
#include <iostream>
void my_function(){
usingnamespace std;
int x=0, y=0; //for user input
cin >> x >> y; //take inputs
int z=x%y; //calculate remainder
if(z>0) //if remainder greater than zero
cout << "The number is a decimal"; //print message
else //otherwise
cout << "The quotient is " << x/y; //print message and answer
}
int main(){
std::cout << "testing..." << std::endl;
my_function();
return 0;
}
OK, makes sense. I just always include using namespace std; in all my coding to this point so I didn't even notice that your code above didn't have it.
Huh, kind of cool, I didn't know you could write it like that, Thanks.