'Problems with cout and a specific string length arithmatic operation c++
This is my first attempt at LCS. The problem I have is with the last portion. When the two input strings are 'mango' and 'man', it seems that cout keeps messing up the 'maxseq-x.length()' part. But it seems fine when storing the result in a variable beforehand or just using printf(). Am I missing something?
#include<bits/stdc++.h>
using namespace std;
int main(){
string x, y;
cin >> x >> y;
int lcs[100][100] = {{0}};
for(int i = 0; i<y.length(); i++){
for(int j = 0; j<x.length(); j++){
if(y[i] == x[j]){
int ans = 0;
if(i && j){
ans = max(1+lcs[i-1][j-1], ans);
}
else{
ans = max(1, ans);
}
lcs[i][j] = ans;
}
else{
int ans = 0;
if(i){
ans = max(lcs[i-1][j], ans);
}
if(j){
ans = max(lcs[i][j-1], ans);
}
lcs[i][j] = ans;
}
}
}
int maxseq = lcs[y.length()-1][x.length()-1];
int z = maxseq-x.length();
cout << maxseq-x.length() << endl;
printf("%d\n", maxseq-x.length());
cout << z << endl;
return 0;
}
Solution 1:[1]
cout
handles maxseq-x.length()
as unsigned value. (This expression contains both signed and unsigned values, so result is unsigned)
%d
in printf
handles maxseq-x.length()
as signed integer
cout << z
handles z
as signed integer.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | WalterWhile |