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.
Related
The calculator program will accept inputs for the 1st number, operation, and 2nd number.
I've set up the program to select the operation with conditional statements. The program does not output however.
I also tried to print out an error message for improper operation selection using xor logic.
I think the problem lies with how I'm using my variables. Any critique or advice is appreciated.
I'm new to learning C++, so I'm trying to make a simple two input calculator. I'm trying to challenge my understanding of variables and conditional statements.
void add_func();
void sub_func();
void mult_func();
void divi_func();
int main()
{
double a;
double b;
char op;
cout << "Input 1st Number:" << endl;
cin >> a;
cout << "Select Operation: (1 = +) (2 = -) (3 = *) (4 = /)" << endl;
cin >> op;
cout << "Input 2nd Number:" << endl;
cin >> b;
if(op == 1)
cout << add_func();
if(op == 2)
sub_func();
if(op == 3)
mult_func();
if(op == 4)
divi_func();
if(op != (1 ^ 2 ^ 3 ^ 4))
cout << "Invalid Operation Selected" << endl;
return 0;
}
void add_func()
{
double a;
double b;
double c;
c = a + b;
cout << a << " + " << b << " = " << c << endl;
}
I've truncated the code to include only the add function. It should be adding the numbers and printing out the result.
I'm pretty sure this: if(op != (1 ^ 2 ^ 3 ^ 4)) isn't doing what you think it is.
The ^ operator is a bitwise exclusive-OR, which gives a 0 bit in the result if both inputs are 0, or if both inputs are 1. If one input is a 1 and the other is a 0, the result is a 1.
The operations are evaluated left to right, so let's work through them one at a time. To make it apparent how a result comes about, we'll include the binary equivalents of the numbers:
1 ^ 2 -> 0001 ^ 0010 -> 0011, which is 3
3 ^ 3 -> 0011 ^ 0011 -> 0000, which is 0
0 ^ 4 -> 0000 ^ 0100 -> 0100, which is 4
So your code is equivalent to: if (op != 4).
You need to use function arguments to pass values between functions. Two variables in different functions are never the same variable even when they have the same name.
And you have to choose whether you are going to do your cout << inside your main function, or inside your add function. You seem to be trying to do both.
Here's how to do it (I choose to do cout << in the add function not the main function).
void add_func(double x, double y);
...
if(op == 1)
add_func(a, b);
...
void add_func(double x, double y)
{
double sum = x + y;
cout << x << " + " << y << " = " << sum << endl;
}
See the parameters in the add function (which I've called x and y, you can call them what you like). And see the a and b variables are passed as arguments when the add function is called.
Your C++ book must talk about function parameters and passing arguments, it's absolutely fundamental to C++ programmming. Time to revise that chapter I think.
please consider using a simple online tutorial to learn the basics.
For example: https://www.tutorialspoint.com/cplusplus/index.htm
or: https://www.w3schools.com/cpp/default.asp
Also, when writing code, try to to pick the simplest solution.
It would get complicated later anyway :)
For a purpose of a simple calculator, a simple switch would suffice.
Please consider the following C code:
#include <iostream>
int main()
{
double a;
double b;
char op;
while(true)
{
std::cout << "Input 1st Number: " << std::endl;
std::cin >> a;
std::cout << "Select Operation: (+) (-) (*) (/) or (x) to exit: " << std::endl;
std::cin >> op;
std::cout << "Input 2nd Number: " << std::endl;
std::cin >> b;
switch (op)
{
case '+':
std::cout << std::to_string(a+b) << std::endl;
break;
case '-':
std::cout << std::to_string(a-b) << std::endl;
break;
case '*':
std::cout << std::to_string(a*b) << std::endl;
break;
case '/':
std::cout << std::to_string(a/b) << std::endl;
break;
case 'x':
return 0;
break;
default:
std::cout << "Invalid Operation Selected" << std::endl;
break;
}
}
}
It is ugly, it has ugly output, but it does the job :)
Try to play around with, for example to achieve nicer output.
Change it from switch statement back to if statements, and add function calls if you want. Learn about the above concepts in the tutorials available online, and do not be shy to ask questions if you get stuck. Failure and failure again is OK, that's how you learn - by trying to get better :)
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.
I am working on a program that generates two random numbers and an if statement that generates either a "+" for addition or a "-" for subtraction. I currently cannot check and see what my putput is so I can correct any mistakes because the program runs my opening "Welcome" statement then displays in blue parentheses (lldb) and the code stops there. I noticed next to my srand(time(0)) function that it turned green and says "thread 1: breakpoint 1.1" and under it reads "Implicit conversion loses integer precision: 'time_t' (aka 'long') to 'unsigned int'". Is there a way to workaround these or get the errors to go away? My code is below. Any help or insight would be appreciated, thanks!
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
int main()
{
cout << "Welcome to the Math Tutor!" << endl;
int N1, N2;
int O = rand() % 2;
int Result;
int Answer;
srand(time(0));
if(O == 2)
{
cout << "+";
}
else
{
cout << "-";
}
N1 = 100 + rand() % 999;
N2 = 100 + rand() % 999;
Result = N1 + O + N2;
cout << setw(10) << N1 << endl;
cout << setw(10) << N2 << O << "\n";
cout << setw(10) << "------\n\n";
cout << "Enter your answer: ";
cin >> Answer;
if(Answer == Result)
{
cout << "You are correct!\n\n";
}
else
{
cout << "You are incorrect, the correct answer is: " << Result << "\n\n";
}
cin.ignore(1);
return 0;
}
time(0) returns a value of type time_t, which apparently is a long on your machine.
When you pass this long to srand(), expecting an unsigned int, not all values of a long will fit in an unsigned int. You can shoehorn it in by using a cast to tell the compiler that you don't care much about this.
srand(static_cast<unsigned int>(time(0)));
As you look for some, more or less, random numbers, the loss of precision is not important in this case.
I'm trying to create a command menu where the user will be able to perform as many commands as he/she wants until pressing "q" which will end the loop. I think I have everything I need to do this except I realized mid-way that my professor asked to use string. When I included string into the program, I began to get error messages saying "could not convert string to bool" wherever there was a while or if statement. What can I do to fix this problem and get my program working. Thanks in advance.
#include <iostream>
#include <string>
using namespace std;
int main()
{
char option;
char number=0;
string s;
string n;
string p;
string q;
char number2;
cout << " Please enter a number: "<< endl;
cin >> number;
do {
cout << " Please enter a command: " << endl;
cout << " s- square the number " << endl;
cout << " n- add the number and (number +1) " << endl;
cout << " p- add the number and (number -1) " << endl;
cout << " q- quit" << endl;
cin >> option;
if (option=s) {
s= number*number;
cout << "Square of this number is : " << s;
}
else if ( option=n){
number2= number+1;
n= number+number2;
cout << "Sum of" << number << "+" << number2 << "is: " << n;
}
else if (option=p) {
number2= number-1;
p= number+number2;
cout << "Sum of" << number << "+" << number2 << "is" << p;
}
else if (option=q)
cout << "Terminating Program";
} while(option);
return 0;
}
you're assigning in the if and else if rather than comparing.
if (option=s) {
should be
if (option=='s') {
note the double =
Also, you need to put single quotes (') around the character choice.
It's a common mistake that even experienced developers make.
These declarations
char number=0;
string s;
string n;
string p;
string q;
char number2;
should all be int
int number=0;
int s;
int n;
int p;
int q;
int number2;
Let me answer as if I were who will evaluate your homework. You have several issues here:
You are asked to use string. Avoid the use of char and string together.
char option; // professor asked to use string: (-1) point
string option; // ok
When you use a single =, like in option="a", you are assigning the value "a" to the variable option. But in the if-else statements you want to compare, so you should use the == comparison operator. Also, you can't compare a char with a string.
if(option = "a") // error: expression must have bool type: (-2) points
if(option == 'a') // error: no operator "==" matches std::string == char; (-2) points
if(option == "a") // ok
You use while(option), but option is declared as a char, not as a bool. Replace this line to while(option!="q") to finish when you enter q.
while(option); // error: expression must have bool type; (-2) points
while(option != "q"); // GOOD!
Also, your program will finish when you scape from the while-statement; so, try to put the "Terminating Program" message after this.
You do not need to declare such many variables (s, n, p, q, number2). Try to use temporary variables inside each scope, for example:
if (option=="s")
{
cout << "Square of this number is : " << number*number << endl;
}
else if ( option=="n")
{
int number2= number+1;
cout << "Sum of " << number << "+" << number2 << " is : " << number+number2 << endl;
}
In the form you write this code, every time you type a new option you will obtain an output like:
Sum of 10+11 is : 21 Please enter a command:
This is ugly to me (-1 point). Try to put a newline (<< endl;) after every cout lines.
Finally, what if I type any other letter not listed in the menu? I would expect a message like Enter a valid option (-1 point).
So I have this program:
#include <iostream>
using namespace std;
bool prime(int input)
{
// cout << "pinput: " << input << endl;
int i = ((input/2) + 1);
// cout << "pi: " << i << endl;
int c;
for (i>0; i--;){
//cout << "pi: " << i << endl;
if (input == 3 || input == 2){
// cout << "true" << endl;
return true;
}
if (input == 1){
// cout << "pi = 1" << endl;
return false;
}
c= input%i;
if (c==0 || i == 1 ){
// cout << "false" << endl;
return false;
}
else if (c!=0 && i<4){
// cout << "true" << endl;
return true;
}
}
return 0;
}
int factor(int input){
// cout << "finput: " << input << endl;
int i = (input/2) + 1;
int c;
int e;
bool d = false;
for (i>0; i--;){
// cout << "fi: " << i << endl;
c = input%i;
if (c==0){
d = prime(i);
if (d==true){
// cout << "found" << endl;
return i;}
}
if (i==1){
// cout << "fi = 1";
return 0;
}
//cout << "not prime" << endl;
}
return 0;
}
int main(){
int woot;
cout << "Please insert quater: " <<endl;
cin >> woot;
int answer;
answer = factor(woot);
if (answer == 0)
cout << "no prime factors" << endl;
else
cout << "answer is: " <<answer << endl;
return 0;
}
It seems to work until I put a really big number in like more specifically the number 600851475143, in which case I always get different answers when I run that number now I'm pretty sure it's just exceeding the size of it's variable type. Now then I was looking and I can't find the right variable type for a number that big, I int and long seem to be for numbers that are for numbers up to 4294967295 if unsigned however that is only 10 digits long, mine is 12. What type of variable should I use? Or will that even fix the problem? The program is to find the largest prime factor of a number (Euler problem 3). Any tips links or advice would be appreciated. And of course an answer extra appreciated! :D
Interesting typo alert!
This is unlikely to be doing what you think it is doing...
for (i>0; i--;){
While it is perfectly legal syntax, and will loop the correct number of times, the value of i inside the loop is (probably) going to be one less than you intended...
% cat 4237157.c++
#include <iostream>
int main()
{
{
std::cout << "Your loop: " << std::endl;
int i = 10;
for (i>0; i--;)
{
std::cout << i << std::endl;
}
}
{
std::cout << "More conventionally: " << std::endl;
for (int i = 10; i > 0; i--)
{
std::cout << i << std::endl;
}
}
return EXIT_SUCCESS;
}
% g++ -o 4237157{,.c++}
% ./4237157
Your loop:
9
8
7
6
5
4
3
2
1
0
More conventionally:
10
9
8
7
6
5
4
3
2
1
The syntax for a for-loop in C-like languages is:
for (variable initialization; conditional; variable increment)
You are evaluating "i>0" instead of doing any initalization. This may as well be blank. Then you are evaluating whether i-- is zero. Since i is post-decremented, your loop starts with i being one less than it was initialized with before the loop, executes until (and including) being equal to zero and then terminates.
A lot of the problems on Project Euler call for arbitrary-precision arithmetic, which isn't covered by the C++ standard library.
Have a look at the C++ Big Integer Library.
If you want arbitarily big numbers, you need an arbitary precision arithmetic library
unsigned long 4294967295
unsigned long long 18446744073709551615
unsigned long long is not standard C++, but most compilers support it as an extension. The maximum should be at least 2^64 - 1, which is more than enough.
If you later want even larger numbers, you can use a arbitrary precision library such as GMP. They have a C++ interface.