简体   繁体   中英

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(). Can anyone tell me why this is happening? Am i missing something simple?

#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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM