mercredi 30 juin 2021

Newbie C++ Questions - Why doesn't this if statement execute?

I have been trying to solve a problem on Codewars and ran into a problem with an if statement executing. If I test the following code, I get the error: "error: use of undeclared identifier 'out'", but if I use the conditional operator instead (see the commented line) everything works fine! I'm probably missing something obvious but could somebody point out why this is?

#include<cmath>
using namespace std;
class Suite2
{
    public:
      static string game(unsigned long long n){
      
      ostringstream os1, os2;
      os1 << pow(n,2)/2;
      os2 << pow(n,2);
      
      if(n%2==0){
        std::string out = "[" + os1.str() + "]";
      }
      else{
        std::string out = "[" + os2.str() + ", " + "2]";
      }
      
      //return (n%2==0) ? "[" + os1.str() + "]" : "[" + os2.str() + ", " + "2]";
      return out;
    }
};

Aucun commentaire:

Enregistrer un commentaire