0
#include "stdafx.h"


int _tmain(int argc, _TCHAR* argv[])
{
int min, max, sumOfSquares;
sumOfSquares = 0;
//scanf_s("%d %d", &min, &max);

while((scanf_s("%d", &min)) != (scanf_s("%d", &max)))
{
    for (int i = min; i <= max; i++)
    {
        sumOfSquares += (i*i);
    }
    printf("%d", sumOfSquares);
    printf("%d %d", min, max);

}

return 0;
}

So basically, I input two integers. One is the min and the next is the max. I get sum of the squares of the min and max and each number in between. I'm not quite sure where it's going wrong. When I input the two numbers, nothing prints out at all, so I'm guessing the while statement is faulty?

Is that not an acceptable format? Can someone please tell me what is wrong and if possible, point me to the right direction.

Also, I used that while loop like that because it should keep asking me for an input and printing out the sumOfSquares until I enter an input that is equal to each other, like 5 5.

Cœur
  • 37,241
  • 25
  • 195
  • 267
bhroask
  • 27
  • 1
  • 8
  • the thing is, C doesn't specify the order of execution, so `scanf_s("%d", &min)` may not be executed before `scanf_s("%d", &max)` and max will be read before min – phuclv Jan 31 '15 at 17:06
  • In C and C++ ["the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is **unspecified**"](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) so if you need to guarentee the order, you must insert a sequence point between the 2 function calls – phuclv Feb 02 '15 at 10:36

1 Answers1

4

scanf_s, like scanf, returns the number of values that were successfully parsed. scanf_s("%d", &min) will return 0, 1 or EOF (for error and end-of-file). As such, the comparison

(scanf_s("%d", &min)) != (scanf_s("%d", &max))

will only be true if only one of min and max could be read, and the values they take do not factor into the result. Moreover, it is undefined in which order the values are read because the order in which the operands of != are evaluated is unspecified.

You probably meant to use something like

while(scanf_s(" %d %d", &min, &max) == 2 && min != max)

Here scanf_s(" %d %d", &min, &max) == 2 will be true if scanf_s reports that it was able to parse two values (you could do this with two calls to scanf_s, but I see no reason to do it), and min != max is, I believe, self-explanatory.

Wintermute
  • 42,983
  • 5
  • 77
  • 80
  • Thank you!! I'll choose your answer in five minutes because it's not allowing me to right now. I did NOT know that although the scanf_s does get the value, it only uses 0 1 based on whether it got it or not. Interesting. Learned something new today :) – bhroask Jan 31 '15 at 17:09