Hi guys,

Quick question, I was trying out to determine the second smallest number of 10 random entered numbers, this is what I got:

``````#include <stdafx.h>
#include <iostream>
#include <iomanip>
using namespace std;

int main(void)
{
int s=0,x=0,y=0;

cout<< "Input ten random numbers with cin and determine the second smallest number"<< endl;

for(int i=0;i<10;i++)
{

cin>> x;cin.get();
if (x<s)
{
s=x;
if (s<y)
{
y=s;
}
}
}

cout<< "The second smallest number is: " << y << endl;
cin.get();

return (0);
}``````

Problem is that s equals zero, and even if I change that, I'm not getting the result I wanted :)

Can any of you guys give me some advice, this is just something that I'm trying out for myself and is not evening school related :!:

Thanks,
JoBe

3
Contributors
4
Replies
5
Views
13 Years
Discussion Span
Last Post by JoBe

I haven't tried the code myself, but at a quick glance, I'd say that you need something like this:

``````if (x < s)
s = x;
else if (x < y) {
s = y;
y = x;
}``````

Greetings,

The algorithm may be off in some ways. I put some prints in the code to see what was failing or skipping and nothing showed up. Firstly the reason that your check of (x<s) will never pass unless x is less that 0. Since s is initialized to 0, x will have to live up to s's expectations.

- Stack Overflow

Darn. I got it wrong.
It's more like this:

``````if (x < s) {
y = s;
s = x;
} else if (x < y) {
y = x;
}``````

Hi guys,

Thanks for the quick responce, it was a combination of both, using your selection gallas and setting the variable s to 100 solved the problem.

Thanks guys, I don't suppose it would work without s being given a certain value that is equal to x :?:

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.