need help C++
Go to solution
Solved by WanderingFool,
Well I agree that you solved it, but your original code was cleaner and easier to edit for the task. You just have a few simple mistakes, by the looks of things.
I'll quickly go through your original code, adding comments
#include <iostream>using namespace std;int main(){int num,first,second;cin>>num;second=num;first=num;while(num>0) { cin>>num; //So you are pretty good up to now, including this line.,,from here you start getting into trouble //So if you want things like -1 to count towards the lowest, then everything is fine. Although if you didn't, -1 would be consider in the later // if statements, so I would recommend just breaking here when num < 0 //if(num < 0) break; at least one problem solved //So there are effectively 3 scenarios here that you want to "deal with". num > second > first, second > num > first, and second > first > num //The first doesn't really matter much, as nothing changes, the second one is important, but the third is effectively where everything happens //so from now on I am assuming second > first > num (actually lets make num = -1 and second and first = 10) if(num<second) //So this is semi-alright *explained later* { second=num; //Over writing second, this makes sense for now...as num is less than second if(second<first) //So when second is lower everything is good. { first=second; //Now the problem surfaces, you already set second = num...now you set first = second, so first = second = num //Actually this problem is pretty easy to solve though, just perform a swap...since second >= first always, swapping will still make that true. //something like //num = second; first = second; second = num; would actually work...instead of your first = second line } }}cout<<first<<endl<<second;}
So essentially your original code could be fixed by inserting just 4 simple lines of code, 2 for if break; and 2 for swapping (swapping is normally 3 but you already have one line of the swap code)

Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now