Infinite loop in do while - c++

I'm new in C++.
I've got a problem with Yi function in my code.
My do while loop in Yi function is never breaking.
I don't know where is the problem. I guess, It's in the bool value, but not sure.
111111111111111111111111111111111111111111111111111111111111222222222222222222233333333333333333333333333333333444444444444444444444444444444444444444444444
there are no more details.
#include "pch.h"
#include <iostream>
#include <iomanip>
#include <limits>
#include <cmath>
using namespace std;
double Yi(double&, double&, double&, int&, int&);
double Yi(double &f, double &a, double &b, int &i, int &n) {
float amin, amax, bmin, bmax, da, db;
bool z = true;
do { cout << "input amin, amax, da" << endl;
cout << "input bmin, bmax, db" << endl;
cout << "Input n" << endl;
while (!(cin >> amin) || !(cin >> amax) || !(cin >> da) || !(cin >> bmin) || !(cin >> bmax) || !(cin >> db) || !(cin >> n)) {
cout << "You have entered wrong input. Input values again: " << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
i = 1;
if ((amax > amin && da > 0) && (bmax > bmin && db > 0) && (n>=i))
{ for (a = amin; a < amax; a += da);
for (b = bmin; b < bmax; b += db);
for (i; i < n; i++);
}
float f1, f2;
if (a == 0)
{
cout << "***********************************************" << endl;
z;
}
if (a > 0)
{
f1 = (a * i + 2 * b) * (a * i + 2 * b) + pow(-1, i)*i;
f2 = sqrt(i*i + i);
f = f1 / f2;
z = false;
}
if (a < 0)
{
f1 = (a * i + 2 * b) * (a * i + 2 * b) + i;
f2 = sqrt(i*i - i + 1);
f = f1 / f2;
z = false;
}
} while (z);
return f;
}
What should I change for working code?
Thank you in advance. :)

I'm not even sure what your Yi function does, however, the boolean value in z is only changed in case a becomes different than zero. Therefore, we may assume a never becomes less neither greater than 0, so your code never enters the block provided by this if if ((amax > amin && da > 0) && (bmax > bmin && db > 0) && (n>=i)) or if it does, this block of code for (a = amin; a < amax; a += da); doesn't execute so a is not less than amax or a is increased until it reaches 0. In case the block headed by the following if if ((amax > amin && da > 0) && (bmax > bmin && db > 0) && (n>=i))
is never executed, a already is set to 0.
Usually one shouldn't copy and paste a code and ask people to fix it, however, since you are new to the forum and also new to c++ programming,I have tried to help you anyway. Also note, it is a good idea to post sample input and output to make it easier to identify the problem. Cheers.

Related

Getting WA, created own test cases too but not getting approved answers

Link of Question : https://www.codechef.com/JULY20B/problems/PTMSSNG
Question Statement
Chef has N axis-parallel rectangles in a 2D Cartesian coordinate system. These rectangles may intersect, but it is guaranteed that all their 4N vertices are pairwise distinct.
Unfortunately, Chef lost one vertex, and up until now, none of his fixes have worked (although putting an image of a point on a milk carton might not have been the greatest idea after all…). Therefore, he gave you the task of finding it! You are given the remaining 4N−1 points and you should find the missing one.
Can anyone suggest where I'm going wrong or update my code or share a few test cases.
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#define ll long long
using namespace std;
int main()
{
int t;
cin >> t;
for (int i = 0; i < t; i++)
{
vector<pair<ll, ll>> v;
ll n, m, a;
bool checkx = false;
cin >> n;
m = 4 * n - 1;
ll x[m], y[m];
ll c, d;
a = (m - 1) / 2;
for (ll i = 0; i < m; i++)
{
cin >> x[i] >> y[i];
v.push_back(make_pair(x[i], y[i]));
}
sort(v.begin(), v.end());
for (ll i = a; i >= 1; --i)
{
if (v[2 * i].first != v[2 * i - 1].first)
{
c = v[2 * i].first;
checkx = true;
if ((2 * i) % 4 == 0 && i >= 2)
{
if (v[2 * i].second == v[2 * i + 1].second)
{
d = v[2 * i + 2].second;
}
else
{
d = v[2 * i + 1].second;
}
}
else
{
if (v[2 * i].second != v[2 * i - 1].second)
{
d = v[2 * i - 1].second;
}
else
{
d = v[2 * i - 2].second;
}
}
break;
}
}
if (checkx)
{
cout << c << " " << d;
}
else
{
if (v[0].second == v[1].second)
{
d = v[2].second;
}
else
{
d = v[1].second;
}
cout << v[0].first << " " << d;
}
cout << endl;
}
return 0;
}
You don't need to do such complex things. Just input your x and y vectors and xor every element of each vector. The final value will be the required answer.
LOGIC :
(a,b)------------------(c,b)
| |
| |
| |
| |
(a,d)------------------(c,d)
See by this figure, each variable (a, b, c, d) occurs even number of times. This "even thing" will also be true for the N rectangles. Hence, you have to find the values of x and y which are occurring odd number of times.
To find the odd one out in such cases, the best trick is to xor every element of the vector. This works because of these properties of xor : k xor k = 0 and k xor 0 = k.
CODE:
#include <functional>
#include <iostream>
#include <numeric>
#include <vector>
signed main() {
std::size_t t, n;
std::cin >> t;
while (t--) {
std::cin >> n;
n = 4 * n - 1;
std::vector<int> x(n), y(n);
for (std::size_t i = 0; i < n; ++i)
std::cin >> x.at(i) >> y.at(i);
std::cout << std::accumulate(x.begin(), x.end(), 0L, std::bit_xor<int>()) << ' '
<< std::accumulate(y.begin(), y.end(), 0L, std::bit_xor<int>()) << '\n';
}
return 0;
}
here is a test case that your code doesn't work:
1
2
1 1
1 4
4 6
6 1
9 6
9 3
4 3
the output of your code is (6,3),but it should be (6,4).
I guess you can check more cases where the rectangles intersects.
from functools import reduce
for _ in range(int(input())):
n=int(input())
li=[]
li1=[]
for i in range(4*n-1):
m,n=map(int,input().split())
li.append(m)
li1.append(n)
r =reduce(lambda x, y: x ^ y,li)
print(r,end=' ')
r =reduce(lambda x, y: x ^ y,li1)
print(r,end=' ')
print()

Prime checker doesn't include some multipliers of the number 10

I need to make a program that will check whether or not the number typed in (a) and its mirrored self (a1) are both prime numbers. I got it to work up to the point where I input a multiplier of 10, in which case it declares it as a prime number, which it clearly isn't.
I've already tried setting the condition:
if ( a % 10 = 0 ) {//declare it as non prime}
After having done that, I would always get a return value of 0 after entering the number. Also tried declaring :
if ( a == 1 ) {//declare it as a non prime}
which fixed it for multipliers of 10 up to 100, but the rest would give me the previously stated error.
My go at it:
#include <iostream>
using namespace std;
int main() {
int a, a1, DN;
cin >> a;
DN = a;
a1 = 0;
for (; a != 0;) {
a1 *= 10;
a1 = a1 + a % 10;
a /= 10;
}
int este_prim, i, este_prim2;
este_prim = 1;
i = 2;
este_prim2 = 1;
while (i < DN && i < a1) {
if (DN % i == 0) {
este_prim = 0;
}
++i;
}
if (a1 > i && a1 % i == 0) {
este_prim2 = 0;
}
++i;
if (a == 1) {
este_prim = 0;
}
if (a1 == 1) {
este_prim2 = 0;
}
if (este_prim2 == 1 && este_prim == 1) {
cout << "DA";
} else {
cout << "NU";
}
return 0;
}
I'm a complete newbie at this so any help would be appreciated. Cheers!
Your loop checks if DN is prime, but it doesn't check if a1 is prime. And this block of code is something I do not understand.
if (a1 > i && a1 % i == 0) {
este_prim2 = 0;
}
So just remove that.
Use this worthy helper function to detect if a positive number is prime:
bool isPrime(int x)
{
if (x <= 1)
return false;
// 2 is the only even prime
if (x == 2)
return true;
// any other even number is not prime
if ((x % 2) == 0)
return false;
// try dividing by all odd numbers from 3 to sqrt(x)
int stop = sqrt(x);
for (int i = 3; i <= stop; i += 2)
{
if ((x % i) == 0)
return false;
}
return true;
}
And then your code to detect if DN and it's mirror, a1 are both prime is this:
int main() {
int a, a1, DN;
cin >> a;
DN = a;
a1 = 0;
for (; a != 0;) {
a1 *= 10;
a1 = a1 + a % 10;
a /= 10;
}
bool este_prim, este_prim2;
este_prim = isPrime(DN);
este_prim2 = isPrime(a1);
if (este_prim2 && este_prim) {
cout << "DA";
} else {
cout << "NU";
}
}

Renaming filenames in two directories IF certain characters between them match - vector subscript out of range

My first job as an intern was to write a program to compare certain characters in the filenames of two different directories, and if they match, rename them. I wrote a custom code to match the characters. The initial few files get renamed in both directories, but it breaks after a point, giving a vector subscript out of range error.
I have an idea of how to fix such a vector range error from all the other posts, but nothing seemed to work. Any input would be appreciated!
PS: I am not a coder and this is my third official program. I understand the code is a bit messy.
Here is the code:
#include<dirent.h>
#include<vector>
#include<sstream>
int main()
{
cout << "Comparer - Renamer v.0.1.beta\n\n";
string dr1, dr2;
int x, y;
DIR *d1;
struct dirent *dir1;
vector<string> a;
a.reserve(25000);
int i = 0;
cout << "Enter the first directory (format : log_2017...) : ";
cin >> dr1;
d1 = opendir(dr1.c_str());
if (d1){
while ((dir1 = readdir(d1)) != NULL){
i++;
a.push_back(dir1->d_name);
}
closedir(d1);
}
x = a.size();
cout << "\nEnter the second directory (format : 2017.12...) : ";
cin >> dr2;
DIR *d2;
struct dirent *dir2;
vector<string> b;
b.reserve(25000);
int j = 0;
d2 = opendir(dr2.c_str());
if (d2){
while ((dir2 = readdir(d2)) != NULL){
j++;
b.push_back(dir2->d_name);
}
closedir(d2);
}
y = b.size();
ostringstream osa, nsa, osb, nsb;
string oldname_a, newname_a, oldname_b, newname_b;
int u, v, w;
for (int l = 2; l < x; l++){
for (int k = l; k < y; k++){
int c = a[l][20] * 10 + a[l][21];
int d = b[k][14] * 10 + b[k][15];
int e = a[l][17] * 10 + a[l][18];
int f = b[k][11] * 10 + b[k][12];
if (a[l][4] == b[k][0] && a[l][5] == b[k][1] && a[l][6] == b[k][2] && a[l][7] == b[k][3] && a[l][9] == b[k][5] && a[l][10] == b[k][6] && a[l][12] == b[k][8] && a[l][13] == b[k][9]){
u = 0;
}
else{
u = 1;
}
if ((e - f) == 0 && abs(c - d) < 12){
v = 0;
}
else{
v = 1;
}
if ((e - f) == 1 && ((c == 58) || (c == 59) || (c == 0) || (c == 1) || (c == 2))){
w = 0;
}
else{
w = 1;
}
if (u == 0 && (v == 0 || w == 0)){
osa.str(string());
osa << dr1 << "\\" << a[l];
nsa.str(string());
nsa << dr1 << "\\" << l - 1 << ". " << a[l];
oldname_a = osa.str();
newname_a = nsa.str();
osb.str(string());
osb << dr2 << "\\" << b[k];
nsb.str(string());
nsb << dr2 << "\\" << l - 1 << ". " << b[k];
oldname_b = osb.str();
newname_b = nsb.str();
rename(oldname_a.c_str(), newname_a.c_str())
rename(oldname_b.c_str(), newname_b.c_str())
break;
}
}
}
return 0;
}
Presently the code is set such that it shows me how the comparison between the filenames is made.
It turns out I was not debugging properly, and the problem was in this part of the code:
int c = a[l][20] * 10 + a[l][21];
int d = b[k][14] * 10 + b[k][15];
int e = a[l][17] * 10 + a[l][18];
int f = b[k][11] * 10 + b[k][12];
I did not know that I couldn't assign an integer from a string/char directly to an int. I converted the char to int (which would give me the ASCII value of the char) and then subtracted it by 48 to convert it to decimal (I do not know if there is an easier way to do this, but this seemed to have worked for me!) The modified part looks like this:
c = ((int)a[l][20] - 48) * 10 + ((int)a[l][21] - 48);
d = ((int)b[k][14] - 48) * 10 + ((int)b[k][15] - 48);
e = ((int)a[l][17] - 48) * 10 + ((int)a[l][18] - 48):
f = ((int)b[k][11] - 48) * 10 + ((int)b[k][12] - 48);
There was also a small manual error in the conditions, which I also rectified.

Exit a while loop with one specific key stroke in C++

I am trying to exit a while loop with this one specific character key input |.
The only way I figured out how is to transform the int user input in char. For some reason, when I input the | character when the program is running, I only receive: Press any key to continue.... My final goal (as I hope is visible from my code) is for the program to actually list all inputs in my vector and then terminate.
I am new to C++ and very lost on this point. If anyone could point me in the right direction I will be very appreciative.
I am running a Windows 8 Entreprise machine.
About the program
This is a simple program that takes user input of integers, adds them to a vector and compares the last two to see which one is bigger, smaller etc.
Full code is here
#include "../../std_lib_facilities.h"
// conversion of units to meters
double funconvert(double x, string unit)
{
const double cm_m = 1.0 / 100.0, in_cm = 2.54, ft_in = 12;
if (unit == "m")
return x;
else if (unit == "cm")
return x = x * cm_m;
else if (unit == "in")
return x = x * in_cm * cm_m;
else if (unit == "ft")
return x = x * ft_in * in_cm * cm_m;
else
cout << "Unknown unit value.\n";
}
// printing the large and the small variables
void printresult(double smallest, double largest)
{
cout << "the smaller value is: " << smallest << "\n";
cout << "the larger value is: " << largest << "\n";
}
int main()
{
vector<double>numbers;
double a, b, smallest, largest;
char the_stop;
string unit;
cout << "Please enter an intiger followed by a measurment unit [e.g 10cm]:";
// Take input
while (cin >> a)
{
char the_stop = a;
cin >> unit;
cout << the_stop;
// check if this is the first number entered
if (numbers.size() == 0)
{
a = funconvert(a, unit);
b = a;
numbers.push_back(a);
numbers.push_back(b);
}
else if (the_stop == '|')
{
// This is not working for some reason... ERROR
sort(numbers);
for (int i = 0; i < numbers.size(); ++i)
cout << numbers[i];
break;
}
else
{
//assign a and b to the last two numbers in a vector
a = funconvert(a, unit);
numbers.push_back(a);
a = numbers[(numbers.size() - 1)];
b = numbers[(numbers.size() - 2)];
// numbers.erase(numbers.begin()); // enable if desire to keep the vector empty
}
// find out which variable is larger and smaller
if (a > b && (a/b-1) >= 0.01)
{
smallest = b;
largest = a;
printresult(smallest, largest);
}
else if (a < b && (b / a - 1) >= 0.01)
{
smallest = a;
largest = b;
printresult(smallest, largest);
}
else if ((a / b - 1) < 0.01 && (a / b - 1) != 0.00 || (b / a - 1) < 0.01 && (a / b - 1) != 0.00)
{
cout << "the nubers are almost equal\n";
}
else
cout << a << " equals " << b << "\n";
}
return 0;
}
Code UPDATED
#include "../../std_lib_facilities.h"
// conversion of units to meters
double funconvert(double x, string unit)
{
const double cm_m = 1.0 / 100.0, in_cm = 2.54, ft_in = 12;
if (unit == "m")
return x;
else if (unit == "cm")
return x = x * cm_m;
else if (unit == "in")
return x = x * in_cm * cm_m;
else if (unit == "ft")
return x = x * ft_in * in_cm * cm_m;
else
cout << "Unknown unit value.\n";
}
// printing the large and the small variables
void printresult(double smallest, double largest)
{
cout << "the smaller value is: " << smallest << "\n";
cout << "the larger value is: " << largest << "\n";
}
int main()
{
vector<double>numbers;
double a, b, smallest, largest;
char the_stop;
string unit;
cout << "Please enter an intiger:";
// Take input
while (cin >> a)
{
// check if the | character is pressed
char the_stop = a;
if (the_stop == '|')
{
cout << "start";
sort(numbers);
for (int i = 0; i < numbers.size(); ++i)
cout << numbers[i];
}
else
{
cout << "And now the unit value:";
cin >> unit;
}
// check if this is the first number entered
if (numbers.size() == 0)
{
a = funconvert(a, unit);
b = a;
numbers.push_back(a);
numbers.push_back(b);
}
else
{
//assign a and b to the last two numbers in a vector
a = funconvert(a, unit);
numbers.push_back(a);
a = numbers[(numbers.size() - 1)];
b = numbers[(numbers.size() - 2)];
// numbers.erase(numbers.begin()); // enable if desire to keep the vector empty
}
// find out which variable is larger and smaller
if (a > b && (a/b-1) >= 0.01)
{
smallest = b;
largest = a;
printresult(smallest, largest);
}
else if (a < b && (b / a - 1) >= 0.01)
{
smallest = a;
largest = b;
printresult(smallest, largest);
}
else if ((a / b - 1) < 0.01 && (a / b - 1) != 0.00 || (b / a - 1) < 0.01 && (a / b - 1) != 0.00)
{
cout << "the nubers are almost equal\n";
}
else
cout << a << " equals " << b << "\n";
}
return 0;
}

Strange output when using atof(optarg)

Edit::
Resolved- This was due to a misunderstanding of the use of the getOpt function.
I referenced the materials in the man here, on stack overflow (http://linux.die.net/man/3/getopt) and the getOpt documentation on GNU's website here: gnu.org/software/libc/manual/html_node/Example-of-Getopt.html Thanks to Bill Lynch and Remyabel for referencing source materials previously mentioned.
there seems to be an issue when I run this program using the -f variable to run the "Football" Commands, alongside using -c, However, I'm primarily concerned on getting just one to work for now.
Placing in the input:
-f -p 16 -a 25 -y 267 -t 1 -i 2
Gives out::
pC = 0
pC = 32738
pY = -1052776240
T = 32738
I = 1
Now, these variables should just be spitting out exactly what I put in, as the only conversion I'm using ( as seen below) is X = atof(optarg);
I suspect this may have something to do with the ASCII values, though I'm almost entirely clueless.
#
#include <iostream>
#include <unistd.h>
#include <cstdlib>
#include <time.h>
#include <stdlib.h>
#include <cmath>
using namespace std;
int main(int argc, char *argv[])
{
srand(time(NULL));
double r = (6 + ( std::rand() % ( 8 - 6 + 1 ) )) / 10;
int c;
int pA;
int pY;
int T;
int I;
int pC;
double mass;
double bMass;
double dist;
double velo;
double Cr = .001;
double k = .18;
double g = 9.8;
double CFdraft;
double Pair;
double Proll;
double Psec;
double timeTravel = 0.0;
double Et;
double E;
double Eavg = 0;
int x = 0;
double cT;
double cC;
double cY;
double cI;
double PasserRating;
while ((c = getopt (argc, argv, "c:m:b:v:d:f:p:a:y:t:i:")) != -1)
{
if (c == 'f') // There seems to be some kind of misunderstanding with what this is doing
// The c=='f' line is there to designate which set of calculations to run, so, that needs to be the //foremost variable to be checked at the beginning of the program.
{
if (c == 'p')
{
pC = atof(optarg);
}
if (c == 'a')
{
pA = atof(optarg);
}
if (c == 'y')
{
pY = atof(optarg);
}
if (c == 't')
{
T = atof(optarg);
}
if (c == 'i')
{
I = atof(optarg);
}
cout << "pC " << pC << endl;
cout << "pC " << pA << endl;
cout << "pY " << pY << endl;
cout << "T " << T << endl;
cout << "I " << I << endl;
//Calculations
cC = ((pC / pA) - 0 / 30) * 5;
cY = ((pY / pA) - 3) * 0.25;
cT = ((T / pA) * 20);
cI = ((2.375) - (I / pA) * 25);
if (cC <= 0)
{
cC = 0;
}
if (cC >= 2.375)
{
cC = 2.375;
}
if (cY <= 0)
{
cY = 0;
}
if (cY >= 2.375)
{
cY = 2.375;
}
if (cT <= 0)
{
cT = 0;
}
if (cT >= 2.375)
{
cT = 2.375;
}
if (cI <= 0)
{
cI = 0;
}
if (cI >= 2.375)
{
cI = 2.375;
}
PasserRating = (((cC + cY + cT + cI) / 6) * 100);
string strPR = "Poor";
if (PasserRating <= 85)
{
strPR = "poor";
}
if (PasserRating > 85)
{
strPR = "mediocre";
}
if (PasserRating > 90)
{
strPR = "good ";
}
if (PasserRating > 95)
{
strPR = "great ";
}
cout << strPR << " " << PasserRating << endl;
}
if (c == 'c')
{
if (c == 'm')
{
mass = atof(optarg);
}
if (c == 'b')
{
bMass = atof(optarg);
}
if (c == 'd')
{
dist = atof(optarg);
}
if (c == 'v')
{
velo = atof(optarg);
}
timeTravel = (dist * 1000) / velo;
cout << "time:" << timeTravel << endl;
cout << "mass " << mass << endl;
cout << "bMass " << bMass << endl;
cout << "dist " << dist << endl;
cout << "velo " << velo << endl;
for (x = 0; x < (10); x ++)
{
CFdraft = r;
Pair = k * CFdraft * (pow(velo, 3));
Proll = Cr * g * (mass + bMass) * velo;
Psec = Pair + Proll;
Et = (Psec * timeTravel);
E = E + Et;
Eavg = E / timeTravel;
}
cout << Eavg << " KJ" << endl;
}
}
return 0;
}
I seriously recommend properly indenting your code. If you did, you would see this:
if(c == 'f'){
if (c == 'p')
...
}
Clearly c is not going to be equal to 'f' and 'p' at the same time.
You never execute your parsing code - everything is inside if(c == 'f') condition, which is obviously true only for the first time you run the loop... So you just get random values from the memory.