简体   繁体   中英

Variable not declared in this scope c++

I am new to c++ and have this program which takes an amount of money and computes the maximum number of 5 dollar bills allowed and assigns it to numFives . The leftover money will be in ones and should be assigned to numOnes . This all assumes that the provided money is 19.

#include <iostream>
using namespace std;

int main() {
   int amountToChange = 0;
   int numFives = 0;
   int numOnes  = 0;

   amountToChange = 19; 
   numFives = amountToChange / 5; 

   numOnes = amountToChange - (numFives * 5); //error occurs here

   return 0;
}

I am assuming my logic is correct here, but whenever I run the code I get this error:

error: ‘numFives’ was not declared in this scope

It seems to be that the variable is initialized properly and I just do not see any issues with the code.

Your logic is correct and so is the code you've posted.

So, unless you've found a serious bug in your compiler, my suggestion is that the code you've posted is not the code causing that error.

My advice is to go back to the code and recheck that you have spelt numFives exactly the same way each time. The fact that it only complains about the variable the second time you try to use it seems to indicate a misspelt variant on the line you mark as the error.

If necessary, delete that line and retype it.

Another possibility is that you've cut and pasted the code from an application that allows strange characters, something I've seen with "smart" quotes amongst other things:

puts (“won't work”);
puts ("will  work");

You can generally find out if that's the case by doing a hex dump of your program such as with the Linux od program:

$ echo "    puts (“won't work”);" | od -xc
0000000    2020    2020    7570    7374    2820    80e2    779c    6e6f
                          p   u   t   s       ( 342 200 234   w   o   n
0000020    7427    7720    726f    e26b    9d80    3b29    000a
          '   t       w   o   r   k 342 200 235   )   ;  \n
0000035

and looking for stuff that doesn't belong. In your case, that would be something around the final numFives occurrence.


As an aside, you could also look into using:

numOnes = amountToChange % 5;

to work out the remainder. It will "fix" your problem in the sense that the error should hopefully disappear but I'd work out the root cause before doing that.

If you're using Visual Studio, you are posting an error given by the Intellisense tool that is responsible for C++ source code tag management.

Intellisense is not a compiler -- if you see that your code is correct, but Intellisense gives an error, that doesn't mean your code is wrong.

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