I use rand function to generate two random numbers, numerator and denominator, that are used in division, sometimes the result is float and sometimes is integer. How can I generate only an integer result ? here is my code :
srand(time(NULL));
integer1 = ((rand() % ( 81 - 5 ) + 5 )*2);
integer2 = ((rand()%3 + 1)*2);
answer = integer1/integer2;
do {
cout << "How much is " << integer1 << " divided by " << integer2 << " ? : " << endl;
cin >> answer;
if (answer == integer1/integer2) {
cout << "Very Good !"<< endl;
}
else {
cout << "Your answer is false, please try again !"<<endl;
}
} while ((integer1/integer2!=answer));
If both operands of / are integral types, the result will be integral. If either operand is a floating point type the result will be a floating point type. If you want it to be a truncated integer you'll need to cast to the type you desire.
Related
So I am creating a program where I have to create random problem sets that have random numbers and operators. I had no problem making random numbers. However, I am confused on how to randomize the three operators I need to use (addition, subtraction, and multiplication). I know I have to use numbers to represent these three operators, but I don't understand how to do that. I have to use the random number generator in order to do this and If & Then statements. Here is my source code.
I've tried creating a separate constant called "const int MAXOP_VALUE = 3" . I am stuck on what to do afterward. How do I represent the addition, subtraction and multiplication operators as numbers?
#include "pch.h"
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
/*Constants*/
const int MIN_VALUE = 1;
const int MAX_VALUE = 100;
/*Variables*/
int number_1;
int number_2;
int math_op;
/*Get the System Time*/
unsigned seed = time(0);
/*Seed the Random Number Generator*/
srand(seed);
/*Generates Random Numbers for the Math Problems*/
number_1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
number_2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
/*Answer to Problem*/
/*Explains How the Program Works*/
cout << "****************************************" << endl << endl;
cout << "Welcome to the awesome math tutor! \n";
cout << "Get ready to add, subtract, and multiply!" << endl << endl;
cout << "****************************************" << endl << endl;
cout << "How much is" << number_1 << math_op << number_2 << "?" <<
endl;
return 0;
}
I expect the output to be along the lines of this:
"What is 25 +42 ?"
"What is 54*3 ?"
"What is 76-2 ?"
One liner for generating random math_op. Remove the int math_op and put this line somewhere after srand(seed).
char math_op = "+-*"[rand() % 3];
And you may use switch-case statement for the actual calcuation.
Once you have the two random numbers, you can use another random number to generate the operation and expected result, something like:
char op; int expected;
switch(rand() % 3) {
case 0: op = '+'; expected = num1 + num2; break;
case 1: op = '-'; expected = num1 - num2; break;
default: op = '*'; expected = num1 * num2; break;
}
Then you'll be able to output the expression and compare what's entered with the expected result:
int answer;
std::cout << "What is " << num1 << " " << op << " " << num2 << "? ";
std::cin >> answer;
std::cout << "Your answer is " << (answer == expected) ? "right" : "wrong" << ".\n";
Normally I'd also suggest you check the expected result is okay, as in no overflow or divide-by-zero, or be wary of doing integer division where 5 / 2 == 2.
But with both numbers between one and a hundred, and divide-by-zero/integral-division being a non-issue as your specifications only allow for addition, subtraction, and multiplication, it should be fine.
This question already has answers here:
What is the behavior of integer division?
(6 answers)
Closed 1 year ago.
Hi guys I'm rather new to programming and working my way through Stroustrup's "Programming, Principles and Practice Using C++" and I've come to a complete standstill at the end of Chapter 3 with an exercise asking you to write a piece of code that does a number of calculations involving 2 numbers which includes finding the ratio of the numbers. Unfortunately this hasn't been covered at all in the book and I'm tearing my hair out trying to figure it out by myself, only able to find examples of code way to advanced for my small little brain.
The code I have at the moment is:
double ratio;
if (val2 > val1)
ratio = (val2 / val1);
if (val2 < val1)
ratio = (val1 / val2);
cout << "The ratio of " << val1 << " and " << val2 << " is 1:" << ratio << '\n';
which works fine for numbers that equate to a whole ratio (e.g. 100 and 25) however despite me setting the variable "ratio" as a double it removes any decimals from the answer in cases of non whole number ratios. Can anyone tell me where I'm going wrong?
When dividing integers the result is integer (integer arithmetics is used):
11 / 2 == 5
11 % 2 == 1 /* remainder */
and when dividing floating point values the result is floating point as well:
11.0 / 2 == 5.5
11 / 2.0 == 5.5
((double) 11) / 2 == 5.5
In your case
double ratio = (val2 / val1);
you have an integer division and only after the disvison performed the outcome of it is cast to double. You can either declare val2 and val1 as double:
double val1;
double val2;
or cast at least one argument of the ratio to double:
double ratio = ((double)val2) / val1;
The fact that result type is double doesn't matter if the original division is performed on integral types (truncating the decimal part).
So to solve your problem, either:
Use a floating point type for the input numbers as well
Cast one of the numbers to a floating point type before division
I did the whole problem from Stroustrup's "Programming, Principles and Practice Using C++. Here is the codes although no comments.
int main()
{
/** --------Numbers-----*/
int val1;
int val2;
double largest; //I'll store here the largest value
double smallest; //I'll store here the smallest value
cout<< " Enter two Numbers to play with\n";
while(cin>> val1>>val2){
if(val1<val2){
cout<< "smallest: "<<val1<<endl;
cout<< "largest: "<<val2<<endl;
//If the above argument succeeds, largest and smallest will get their values
largest=val2;
smallest=val1;}
if(val1>val2){
cout<< "smallest: "<<val2<<endl;
cout<< "largest: "<<val1<<endl;
//If the above argument succeeds, largest and smallest will get their values
largest=val1;
smallest=val2;}
int their_sum=val1+val2;
int their_product=val1*val2;
int their_diff=val1-val2;
double ratio1;
ratio1=largest/smallest;
cout<<"Sum: "<<their_sum<<endl;
cout<<"Difference: "<<their_diff<<endl;
cout<<"Product: "<<their_product<<endl;
cout<<"Ratio: "<<ratio1;
}
return 0;
}
There is nothing new in this code, everything was covered in the previous chapters.
If at all you need ratio of two numbers say a,b in the form of n:m (where n>=1) then simply find the GCD(a,b) and divide a,b with this result.
eg:
a=4,b=6;
GCD(a,b)=2;
n=4/2=>2
m=6/2=>3
so ratio of 4 and 6 is 2:3
#include<iostream>
using namespace std;
class Test
{
public:
void check()
{
int x,y;
cout<<"Enter 1st number";
cin>>x;
cout<<"Enter 2nd number";
cin>>y;
int a;
int d= gcd(x,y);
cout<< x/d << " : " << y / d << endl;
}
int gcd(int x, int y) // 14, 21
{
int d;
if(y>x)
{
y=x+y;
x=y-x;
y=y-x;
}
for(int i=1; i<=y; i++)
{
if(x%i==0 && y%i==0 )
{
d=i;
}
}
return d;
}
};
int main()
{
Test t;
t.check();
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int val1,val2;
cout << " Enter two integer values followed by enter" << endl << endl;
cin >> val1;
cin >> val2;
if(val1 < val2) // To determine which value is larger and which one is smaller
{
cout << val1 << " is smaller than" << val2 << endl << endl << "And" << val2 << " is larger than " << val1 << endl<<endl;
}
enter code here
else if( val2 < val1)
{
cout<<val2 <<" is smaller than"<< val1<<endl<<endl<<"And"<< val1 << " is larger than "<< val2<< endl << endl;
}
cout << "The sum of "<< val1<<" and "<<val2<<" is "<< val1+val2<<endl<<endl;
// diplaying the sum of the two numbers
enter code here
cout << " The difference between "<<val1<< " and "<<val2<< " is " << val1-val2<<endl;
// displays the difference of val2 from val1
cout << " The difference between "<<val2<< " and "<<val1<< " is " << val2-val1<<endl;
// displays thr difference of val1 fromval2
enter code here
enter code here
cout << " The product of " <<val1<< " and " << val2<< " is " << val1*val2<< endl<<endl;
// displaying the product of val1 and val2
enter code here
enter code here
enter code here
// now to diplay the ratio of the two numbers
double ratio1;
cout << " The ratio of "<<val1<<" and "<<val2<<" is ";
if(val1 < val2)
{
ratio1= ((double)val2) /val1;
cout << ratio1;
}
else if(val1 > val2)
{
ratio1= ((double)val1) /val2;
cout << ratio1;
}
}
I get an error message that states "expected primary-expression ';' token" and it highlights my percentage formula. I have tried to rearrange my code, but it seems the problem is not in it.
const int TOTALSUITES = 120;
for (int floor = 10; floor <= 16; floor++) {
if ( floor != 13) {
do {
cout << "Please enter the number of suites occupied on the floor " << floor << ":";
cin >> numOccupied;
if ((numOccupied <0) || (numOccupied >20 )) {
goodChoice = false;
cout << "\n\t\t**ERROR" << numOccupied << " ***\n\n";
cout << "*** Choice must be from [0-20]***\n";
}
else {
goodChoice = true;
}
totalOccupied += numOccupied;
} while (!goodChoice);
}
}
percentage = (totalOccupied / TOTALSUITES) * 100% ;
cout << endl;
cout << "Hotel has " << TOTALSUITES << endl;
cout << "Number of occupied suites is " << totalOccupied << endl;
cout << "The percentage of occupied suites is " << percentage << endl;
system("pause");
return 0;
% used here is the modulo operator which is a binary operator...
so this is what you have to do...
percentage = (totalOccupied / TOTALSUITES)* 100;
//and then where you have cout percentage at that point...do this
cout<<"the percentage of occupied suites is"<<percentage<<"%";
100% is not 100 percent. 100% is trying to use the % operator in an incorrect manner. To multiply by 100% you just use 1 which is not needed as anything times 1 is itself.
percentage = (totalOccupied / TOTALSUITES) * 100% ;
This is not valid syntax. Change it to this.
percentage = (totalOccupied / TOTALSUITES);
Assuming your totalOccupied is not a float, you should probably do this as well:
percentage = (static_cast<float>(totalOccupied) / TOTALSUITES);
% is actually the modulus operator in C++, requiring two arguments.
100% is therefore not syntactically valid.
Assuming that you want % to stand-in for a "divide by 100" operator, the simplest thing to do in your case is to drop the 100% from your code.
Note that totalOccupied / TOTALSUITES will be carried out in integer arithmetic if totalOccupied is also an int or unsigned. Fix that by promoting one of the arguments to a double, or pre-multiply the term with 1.0.
I know that the unsigned long is up to 4294967295 only, so here's my problem, when the user inputs many numbers (like the result is going to exceed on the limit) the converted number will be just 4294967295.
example:
Base 11: 1928374192847
Decimal: 4294967295
the result should be 5777758712535. how to fix this limit ? vb6.0 required to us.
here's my code:
cout << "\t\t CONVERSION\n";
cout << "\t Base 11 to Decimal\n";
cout << "\nBase 11: ";
cin >> str;
const auto x = str.find_first_not_of("0123456789aA");
if (x != string::npos)
{
std::cout << "Invalid Input\n\n";
goto a;
}
unsigned long x = strtoul(str.c_str(), NULL, 11);
cout << "Decimal: " << x << "\n\n";
The program should say "out of range" if the result will exceed 4294967295.
Sorry im just a beginner.
From the strtoul docs on www.cplusplus.com :
If the value read is out of the range of representable values by an unsigned long int, the function returns ULONG_MAX (defined in <climits>), and errno is set to ERANGE.
You should check the errno to determine if the value was out of range.
This question already has answers here:
Can't use modulus on doubles?
(4 answers)
Closed 9 years ago.
Im not being allowed to use mod. I think it's not working because I'm using doubles; is there a way around this? --- the commented areas arnt working
void displayResults(double num1, char oper, double num2)
{
switch(oper)
{
case '+' :
cout << num1 << "+" << num2 << "=" << (num1+num2) << endl;
break;
case '-' :
cout << num1 << "-" << num2 << "=" << (num1-num2) << endl;
break;
case '*' :
cout << num1 << "*" << num2 << "=" << (num1*num2) << endl;
break;
case '/' :
if ( num1==0 || num2==0)
cout <<"A number divided by 0 or divided into 0 is always 0"<< endl;
else
cout << num1 << "/" << num2 << "=" << (num1/num2) /*+ (num1%num2) */ << endl;
break;
// case '%' :
// cout << num1 << "%" << num2 << "=" << (num1%num2);
//break;
}
}
Use std::fmod. It has an overload for doubles:
#include <cmath>
std::fmod(num1, num2);
The modulus operator % is an integral function.
You need to use fmod for floating-point.
% is only allowed for integral types or unscoped enums, you can use std::fmod for double:
#include <cmath>
#include <iostream>
int main() {
double num1 = 5.5;
double num2 = 3.0;
double z = std::fmod(num1,num2);
std::cout << z << std::endl ;
return 0;
}
Of course, you could overload the '%' operator to perform the modulus operation on any type you like. There is no build-in support in the language for doubles, however.
i think you can rather replace your doubles with 'long int' , that will help you overcome the error and this will also work with all integer based operations.
i made this change in one of my codes and got it right, with a warning though. But it did work just fine, so try that, it should work pretty well.