Programme is terminating in c++; - c++

I have written the code which will print the slope from the coordinates of a line and then print it. but when I give input, my code is terminating. what is the problem?
#include<bits/stdc++.h>
using namespace std;
int main()
{
int x1,y1,x2,y2,m;
cin>>x1>>y1>>x2>>y2;
m=(y1-y2)/(x1-x2);
cout<<m;
}

Problem is probably here m=(y1-y2)/(x1-x2);. When x1==x2 you have division by zero, please add some checks.

Consider adding more corner tests, also note when x1 is equal to x2 you will face division by zero error, so you should modify your program with if statement to check that they are not equal.
so you should add this to your code:
if(x1==x2){
cout<<"Error division by zero"<<endl;
return 1;
}

I tested your code using c++ compiler online and it worked.
You may have a compiler error or something else.

Related

Explanation for weird behavious when ios::sync_with_stdio(0) and cin.tie(0) are written inside loop

The input I am giving is
5
1 1 1 1 1
Can someone explain me this behaviour?
I actually found this during a online competitive programming contest. I was getting wrong answer verdict. While on my computer it worked fine, online IDEs gave a runtime error (Bus error). So I tried the below code (which is actually different than the original problem solution) but the principle I guess remains the same. If I get enough insight from this explanation, I might also understand the original solution errors. If not I will put additional queries.
#include <iostream>
using namespace std;
int main()
{
int t, a = 9;
cin >> t;
while(t--)
{
ios::sync_with_stdio(0);
cin.tie(0);
cin >> a;
cout << a;
}
}
The below code when run on online ide gives output as:
99999
(I tested on codechef.com/ide and ide.geeksforgeeks.org)
While on my computer terminal (Ubuntu, g++) it gives output as:
11111
(This is true when I pass a input file to it or manually enter data in terminal)
This weird behavior is only when the two statements are inside the while loop. When written above the while loop, the output is as expected.
According to cppreference:
If [ios::sync_with_stdio] is called after I/O has occurred on the standard stream, the behavior is implementation-defined: implementations range from no effect to destroying the read buffer.
So you should not be calling this function inside your loop. Instead, just call it once at the start of main:
https://wandbox.org/permlink/fhpRNUGCXDef1bw4

Special Fibonacci and SIGSEGV

#include<bits/stdc++.h>
#define big 1000000007
using namespace std;
long long n,k;
int fobo(int);
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
k=fobo(n)%big;
printf("%d",k);
printf("\n");
}
return 0;
}
int fobo(int m)
{
if(m==1)
return 0;
if(m==2)
return 1;
return 3*fobo(m-1)+2*fobo(m-2)+5;
}
The above code is for printing the sum of a special kind of Fibonnacci series following the relation given in the recurrence relation inside the function fobo . The code works fine on my machine but on testing in any online judge , the same code shows SIGSEGV error. There is no use of any arrays in the program , accessing unknown memory that i know of. I guess these are the some of the major requirements for having a SIGSEGV error. I cant find any in here . Please help me in resolving or finding the error.
If I had to guess, this looks like a stack overflow error. Try feeding 0 into fobo. When that happens, your base cases don't trigger because neither one checks for zero. You then call fobo(-1) and fobo(-2), which will start a chain of recursive calls of the form fobo(-2), fobo(-3), fobo(-4), etc. until you eventually overflow the stack.
To fix this, consider adding in a new base case for 0 in your code, or alternatively put in a general check to handle the case where the input is negative.
EDIT: Based on the comments, I think the main issue here is that if you call this function with a large input, you'll get a stack overflow before the recursion terminates. To address this, consider computing your values bottom-up using dynamic programming. I suspect that's what the question is ultimately trying to get at. Alternatively, use a different recursive formulation amenable to tail call elimination. If you're not familiar with these techniques, look online - you'll learn a lot in the process!

how come my c++ code gives 2 different outputs in ideone and codeforces custom test?

ideone:https://ideone.com/Ba3Nw7
#include <iostream>
using namespace std;
int main() {
int i,n,b25,b50,temp;
cin>>n;
for(i=0;i<n;i++)
{
cin>>temp;
if(temp==25)
b25++;
else if(temp==50)
{
if(b25>0)
{
b25--;
b50++;
}
else
{
cout<<"NO";
return 0;
}
}
else if(temp==100)
{
if(b25>0 && b50>0)
{
b25--;
b50--;
}
else if(b25>2)
b25-=3;
else
{
cout<<"NO";
return 0;
}
}
}
cout<<"YES";
return 0;
}
the test case tried is:
2
25 100
the output on ideone is "NO" which is the correct answer but on the codeforces custom test it gives a "YES",why is that?
One very glaring mistake I can see is not initialising variables b25 and b50.
In your code, you are continuously incrementing and decrementing the two variables, and therefore, your answer goes wrong every time.
I would suggest:
int i,n,b25=0,b50=0,temp=0;
You might be getting a right or a wrong answer because arbitrarily any value can get stored in b25 and b50. Sometimes it may satisfy the NO condition, and at other times, a YES condition.
Had your variables been static or within file scope, they would have been initialised as 0. However, your variable is locally defined, hence its value will be indeterminate, invoking undefined behaviour.
You are using the variables b25, b50 uninitialised, but guessing from your code you assume them to be initially zero.
Their initial value can currently differ from run to run, so putting it a second time on one of those platforms may give more different results. (Unless ideone uses BSD or something where memory is initially zero by default)

Numbers positive and negative

What am i doing wrong? I want to have a random numbers. Negative and positive integers
#include <iostream>
#include <cstdlib>
int main(){
int a;
cin<<a;
int t[a];
for(int i=0;i<a;i+=1)
t[a]=rand();
for(int i=0;i<a;i++)
cout>>t[i];
}
Im very beginner and I wanted to have random numbers but i have only one very big.
Can anybody help?
Sorry, but you see problems which i haven't. Now i know i should only write >>endl
EDIT:
I corrected my code and it works now
#include <cstdlib>
#include <time.h>
int main(){
int a;
cin>>a;
for(int i=0;i<a;i++)
cout<<(rand()-rand())<<endl;//i asked only for this "endl"
}
You haven't seeded the random number generator. Call srand() at the start of your program.
The usual way is to call it with whatever current time is:
std::srand(std::time(0))
You'll need to include <ctime>, too.
Note that rand() doesn't return negative values, that logic you'll need to implement by yourself.
cin<<a;
Here, you're using the wrong operator. Think of the angle brackets as showing the flow of data. You want:
cin>>a;
Similarly with cout:
cout<<t[i];
You are also indexing t with a, rather than with i, in the first for loop:
t[i]=rand();
//^ This is i, not a
Another problem is that you are using a compiler extension to create an array of run-time size. That is, with standard C++ you cannot use a as the size of your array since it is not known at compile time.
t[i]=rand();
not
t[a]=rand();
or did you write that wrong too?
I'm not sure at 100% but IMO, rand() can create only positive numbers, from 0 to 65535, depending on the time that the executable was compiled: this mean that once you had compiled the .exe file, it will give the same numbers over and over again!
In order to make him produce different numbers you have to use srand().
Another thing:
In C++ you can't allocate a dynamic array with type array[n] [it isn't in the standard!], even if the compiler allows you to do it!
Actually the compiler translate your code in array = new type[n] that you have to deallocate with the delete[] keyword.

display multiple errors via bool flag c++

Been a long night, but stuck on this and now am getting "segmentation fault" in my compiler..
Basically I'm trying to display all the errors (the cout) needed. If there is more than one error, I am to display all of them.
bool validMove(const Square board[BOARD_SIZE][BOARD_SIZE],
int x, int y, int value)
{
int index;
bool moveError = true;
const int row_conflict(0), column_conflict(1), grid_conflict(2);
int v_subgrid=x/3;
int h_subgrid=y/3;
getCoords(x,y);
for(index=0;index<9;index++)
if(board[x][index].number==value){
cout<<"That value is in conflict in this row\n";
moveError=false;
}
for(index=0;index<9;index++)
if(board[index][y].number==value){
cout<<"That value is in conflict in this column\n";
moveError=false;
}
for(int i=v_subgrid*3;i<(v_subgrid*3 +3);i++){
for(int j=h_subgrid*3;j<(h_subgrid*3+3);j++){
if(board[i][j].number==value){
cout<<"That value is in conflict in this subgrid\n";
moveError=false;
}
}
}
return true;
}
If this is a chess board, then:
for(index=0;index<9;index++)
should be:
for(index=0;index<8;index++)
Or even better:
for(index=0;index<BOARD_SIZE;index++)
If you've got named constants, always use them in place of magic numbers.
check your indices. As you are using a fixed sized array, it might be an off-by-one error
To find out the exact line that is triggering your SEGFAULT, compile with the flag -ggdb (I'm assuming you are using GCC), and then run your program using gdb (using gdb ./name_of_the_program). When GDB starts up, use run to start the program. It will break at "main", and then execute continue. Let it run until it SEGFAULTs. Once it has segfaulted, execute backtrace (or, bt for short) to get a backtrace of the program execution. The backtrace should include the exact line that caused the SEGFAULT.
With the information that you get out of GDB, you should be able to debug your program. However, if you need more help than that, provide us with the output from backtrace so that we can be of more help.
1) Use this function instead of directly board[x][index], etc.:
const Square& GetSquare(
const Square board[BOARD_SIZE][BOARD_SIZE]&,
int x,
int y)
{
assert(x >= 0);
assert(x < BOARD_SIZE);
assert(y >= 0);
assert(y < BOARD_SIZE);
return board[x][y];
}
Test that you are on debug so that assert(false) gives an error message. Write assert(false), see the message, then delete this line. Without these assertions, I simply cannot trust your code.
2) Do not use magic numbers 9 and 3.
3) Take into account that int v_subgrid=x/3; may have a nonzero remainder, e.g., 7/3=2 and the remainder is 1. And 2/3=0. If this is what you want, ok. Just take it into account.
I expect your seg value might be in the following section... (as well as mentioned above (using 9 instead of BOARD_SIZE) for the proir two for-loops )...
for(int i=v_subgrid*3;i<(v_subgrid*3 +3);i++){
for(int j=h_subgrid*3;j<(h_subgrid*3+3);j++){
if(board[i][j].number==value){
cout<<"That value is in conflict in this subgrid\n";
moveError=false;
}
}
I would recommend you write some robust tests for functions such as yours (unit tests). Passing in values of X or Y that are set to BOARD_SIZE - 2 or above would mean indexing out of the array size of the board.
What I'm trying to get across is, code really need to be in place to stop indexing out of bounds,
hope this also helps,
Neil