So basically I am trying to get it to stop repeating. If I enter numbers correctly it works fine. If I enter negative numbers which are not allowed and needs a try-catch exception it keeps repeating and won't stop asking for numbers.
All I have is this source file for the code and I am trying to make a function for main.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void gcd(int x, int y);
int main()
{
int x;
int y;
cout << "Please enter two integer values" << endl;
cin >> x;
cin >> y;
gcd(x, y);
return 0;
}
void gcd(int x, int y)
{
int gcd;
int s = 0;
while (s == 0)
{
try
{
if (x < 0 || y < 0)
throw 1;
else
{
s == 1;
break;
}
}
catch (int x)
{
cout << "Wrong negative input please type in two Positive integers" << endl;
cin >> x >> y;
continue;
}
}
for (int i = 1; i <= x && i <= y; i++)
{
if (x % i == 0 && y % i == 0)
gcd = i;
}
cout << "The gcd of x: " << x << " and y: " << y << " is: " << gcd << endl;
}
If you don't want your function gcd() to be called with negative values, throw a std::invalid_argument exception. It is not the business of gcd() to request user input. Validate the input in main() before you call gcd().
#include <limits>
#include <stdexcept>
#include <iostream>
int gcd(int, int);
int main()
{
int x, y;
while (std::cout << "Please enter two positive integers: ",
!(std::cin >> x >> y) || x < 0 || y < 0)
{
std::cerr << "Input error :(\n\n";
if (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
std::cout << "The gcd of x: " << x << " and y: " << y << " is: " << gcd(x, y) << "\n\n";
}
int gcd(int x, int y)
{
if (x < 0 || y < 0)
throw std::invalid_argument("No negative arguments to gcd(), please :(");
return y == 0 ? x : gcd(y, x % y);
}
You can (and perhaps should) remove the logic from gcd function and instead place it where you get your input from user, that is, in main. Also, state the requirements up front. For example:
int main()
{
int x;
int y;
cout << "Please enter two positive integer values" << endl;
cin >> x;
cin >> y;
if (x < 0 || y < 0)
{
cout << "Wrong negative input please type in two Positive integers" << endl;
return 0;
}
gcd(x, y);
return 0;
}
Now, you can place assertions in gcd to enforce no negative values get in:
void gcd(int x, int y)
{
assert(x >= 0);
assert(y >= 0);
// ...
}
Related
i am not sure how to resolve this math problem. what should i recall and where did i miss something. i have tried different opportunities. i think i just call not existing index or something like that..
#include <iostream>
using namespace std;
double recur(int n, int x);
double x;
int number;
int main()
{
cout << "enter n: " ;
cin >> number;
cout << endl;
do
{
cout << "enter float x!=0: ";
cin >> x;
cout << endl;
} while (x==0);
cout << "recur(" << number << "," << x << ")=" << recur(number, x) << endl;
system("pause");
}
double recur(int n, int x)
{
if (n > 1) return (x * recur(n, x - n) * recur(n - 1, x));
else if( n == 1) return x * recur(n,x) - x;
else return 1;
}
Formula:
For formula:
It's implementation:
#include <iostream>
#include<cmath>
using namespace std;
double recur(int n, int x);
double x;
int number;
int main()
{
cout << "enter n: " ;
cin >> number;
cout << endl;
do
{
cout << "enter float x!=0: ";
cin >> x;
cout << endl;
} while (x==0);
cout << "recur(" << number << "," << x << ")=" << recur(number, x) << endl;
system("pause");
}
double recur(int n, int x)
{
if (n > 1) return (x*(pow(log(x),n)) - n*(recur(n-1,x)));
else if( n == 1) return x * log(x) - x;
}
For n>1 line
(x*(pow(log(x),n)) = x*(ln x)^n
n*(recur(n-1,x)) = n* integral( (lnx)^(n-1) ) <- In next recursion call one power will get reduced
For n=1 line
x * log(x) - x = xlnx - x <- base condition(where recursive call will stop)
In this implementation recur(n,x) denotes integration of (lnx)^n w.r.t x.
Your integral isn't the same as the log portion, so you should probably split that out.
double ln_n(int n, double x) {
while (n --> 0) x = log(x);
return x;
}
double integral(int n, double x) {
if (n > 0) return (x * ln_n(n, x)) - (n * integral(n - 1, x));
return x;
}
See it live
I'm just starting so I'm trying to write a program which determine if a number is positive or negative.
#include <iostream>;
int step_function(int x) {
int result = 0;
if (x > 0)
result = 1;
else if (x < 0)
result = -1;
else
result = 0;
return result;
}
using namespace std;
int main() {
int num;
cout<< "please enter number : ";
cin >> num;
int a = step_function(num);
if (a == 1)
printf("%d is positive", num);
else if (a == -1)
printf("%d is negative", num);
else
printf(" it is zero");
return 0;
}
There is a few things you should do:
First things first you should get yourself a Good Book for C++.
Second thing is read why using namespace std; is a bad idea.
Lastly here is your code fixed. You needed to remove the semicolon as well as removing the printf(). I also removed the using namespace std; which made it more readable.
#include <iostream>
int step_function(int); //Function prototype
int main() {
int num;
std::cout << "please enter number : ";
std::cin >> num;
int a = step_function(num);
if (a == 1)
std::cout << num << " is postive";
else if (a == -1)
std::cout << num << " is negative";
else std::cout <<" it is zero";
return 0;
}
int step_function(int x)
{
int result = 0;
if (x > 0) result = 1;
else if (x < 0) result = -1;
else result = 0;
return result;
}
Don't use semicolon after #include <iostream>.
I think for C++ cout is more standard whereas printf is from C.
You can also include printing of the text in the step_function. Also, it's better to use braces {} after if and else statements for clarity especially if the code becomes complex.
#include <iostream>
using namespace std;
void step_function(int x) {
if (x > 0) {
cout << x << " is positive" << endl;
}
else if (x < 0) {
cout << x << " is negative" << endl;
}
else {
cout << "it is zero" << endl;
}
}
int main() {
int num;
cout<< "please enter number : ";
cin >> num;
step_function(num);
return 0;
}
So after learning some Python, I decided to check out C++ and give it a try and decided to try and code Collatz Conjecture in Xcode.
Here's what I got.
#include <iostream>
int collatz() {
std::cout << "Enter a number: ";
int x = 0;
std::cin >> x;
while (x != 1) {
if (x % 2 == 0) {
x /= 2;
std::cout << x << " ";
} else {
x = (3 * x) + 1;
std::cout << x << " ";
}
}
return 0;
}
int main() {
collatz();
}
Extra Question: In Python there is condition called elif, how is it called in C++?
#include <iostream>
int collatz() {
std::cout << "Enter a number: ";
int x;
std::cin >> x;
while (x != 1) {
x = x % 2 ? x / 2 : x * 3 + 1;
std::cout << x << ", ";
}
std::cout << "\b\b \b\b" << std::endl;
return 0;
}
int main() {
collatz();
}
You can do something like this if you don't want comma at last
Add a check not to add comma for last digit
#include <iostream>
int collatz() {
std::cout << "Enter a number: ";
int x = 0;
std::cin >> x;
while (x != 1) {
if (x % 2 == 0) {
x /= 2;
std::cout << x ;
} else {
x = (3 * x) + 1;
std::cout << x ;
}
if (x!=1)
std::cout<<",";
}
return 0;
}
int main() {
collatz();
}
Output
Enter a number: 5
16,8,4,2,1
Using your original code (I see you've edited it), you can do this if you want to avoid an extra conditional and multiple calls through cout in your loop.
#include <iostream>
#include <iostream>
#include <sstream>
int collatz()
{
std::cout << "Enter a number: ";
int x = 0;
std::cin >> x;
std::string output;
while (x != 1)
{
if (x % 2 == 0)
{
x /= 2;
output += std::to_string(x) + ", ";
}
else
{
x = (3 * x) + 1;
output += std::to_string(x) + ", ";
}
}
output.replace(output.rfind(',', output.length()), 2, "");
std::cout << output.c_str();
return 0;
}
Probably the only thing that needs explaining here is output.replace(). rfind() finds the last comma, starting at the end. replace then clobbers the two characters at that position (", ").
I want to print three number from maximum to minimum for 3 numbers, when I try to compile this code it shows me this error C2065 "function parameter :Undeclared identifier function parameter"for every function arguments . other error is C 2062 type "int" unexpected.
Here is my code
#include "stdafx.h"
#include <iostream>
using namespace std;
int max, min;//making global variable of max and min
void numMax(int x, int y, int z);//finding maximum number
void numMin(int x, int y, int z);/finding minimum number
int main()
{
int x, int y, int z;
int middle = 0;
cout << "This program will take 3 number and print them from minimum to maximum" << endl;
cout << "_________________" << endl;
cout << "Pleas enter three number" << endl;
cout << "num1 =";cin >> x;cout << endl << "\n";
cout << "num2 =";cin >> y;cout << endl << "\n";
cout << "num3 =";cin >> z;cout << endl << "\n";
numMax(x, y, z);
numMin(x, y, z);
if (x<max & x>min)
{
middle = x;
}
if (y<max & y>min)
{
middle = y;
}
if (z<max & z>min)
{
middle = z;
}
cout <<"ordered numbers are : "<< min << "\t"<< middle << "\t" <<max ;
return 0;
}
void numMAx(int x, int y, int z)
{
int max;
max = x > y ? x : y;
max = z > max ? z : max;
cout << max;
}
void numMin(int x, int y, int z)
{
int min;
min = x < y ? x : y;
min = min<z ? min : z;
cout << min;
}
first I have defined my functions, then in main function I have passed parameter to function argument then I have mentioned my numMax and numMin fuctions to excute their task. finally I have used if statement for determining middle number. What should I do ?
int numMax (int x,int y ,int z)
{
if(x>y && x>z)
return x;
else if (y>x && y>z)
return y;
else
return z;
}
int numMin(int x,int y ,int z)
{
if(x<y && x<z)
return x;
else if (y<x && y<z)
return y;
else
return z;
}
void main()
{
int x,y,z;
int max,min;
clrscr();
cout<<"\n Enter 3 Number: \n";
cout<<"1st Num: ";cin>>x;
cout<<"2nd Num: ";cin>>y;
cout<<"3rd Num: ";cin>>z;
max = numMax(x,y,z);
min = numMin(x,y,z);
if(x<max && x>min)
{
middle=x;
}
else if(y<max && y>min)
{
middle=y;
}
else
middle=z;
cout<<"Number from max to min are: \n "<<numMax(x,y,z)<<" "<<numMin(x,y,z)<<" "<<middle;
}
try this
#include "stdafx.h"
#include "math.h"
#include <string>
#include <iostream>
using namespace std;
int main ()
{
int x;
cout << "Enter a number." << endl;
cin >> x;
int y = 1;
int i = 0;
while (i == 0 && y < sqrtf(x))
{
if (fmodf(x,y) == 0)
{
i = 1;
}
else
{
i = 0;
}
y++;
if (i == 1)
{
cout << "Your number is prime." << endl;
}
else
{
cout << "Your number is composite." << endl;
}
}
return 0;
}
This is a code I created to test for primes. After sorting out several debugging issues I was able to run it.
It opened the command window, read 'Enter a number' and closed itself the second I entered a number.
Help?
You have to:
close the while loop in the correct place
change the if (i == 1) condition (i==1 means x is divisible by some y)
start with y = 2 (every number is divisible by one)
include sqrtf(x) in the loop (y <= sqrtf(x) or 15, 25, 35... are primes).
So:
int main()
{
int x;
cout << "Enter a number." << endl;
cin >> x;
int y = 2; // <-- changed
int i = 0;
while (i == 0 && y <= sqrtf(x)) // <-- changed
{
if (fmodf(x,y) == 0)
{
i = 1;
}
else
{
i = 0;
}
y++;
} // <-- moved here
if (i == 0) // <-- changed
{
cout << "Your number is prime." << endl;
}
else
{
cout << "Your number is composite." << endl;
}
return 0;
}
works (more or less...).
Anyway:
don't use using namespace std; (Why is "using namespace std" considered bad practice?)
\n should be your default ("\n" or '\n' or std::endl to std::cout?)
y and x are integers so you can use % instead of fmodf
avoid premature pessimization: prefer preincrement, only use postincrement if you're going to use the original value
else { i = 0; } is superfluous
you can change y < sqrtf(x) with y * y <= x (and you don't need math.h anymore) or find square root of number then start the loop
Somewhat better (but far from perfect):
#include <cmath>
#include <iostream>
int main()
{
int x;
std::cout << "Enter a number.\n";
std::cin >> x;
int square_root = std::sqrt(x);
int y = 2;
int i = 0;
while (i == 0 && y <= square_root)
{
if (x % y == 0)
i = 1;
++y;
}
if (i == 0)
std::cout << "Your number is prime.\n";
else
std::cout << "Your number is composite.\n";
return 0;
}
Now:
input validation, i.e. check for bad input values (How to check if input is numeric in C++)
special cases checking (is the number one a prime number?)
a bool would express your intentions better than int i;
improve the algorithm (Determining if a number is prime, Which is the fastest algorithm to find prime numbers?, Primality tests)