问题
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <math.h>
I need help with this code. My compiler keeps asking me to use the -fpermissive option but I don't know where to input it. I've pasted the code below and the error that is shown.
using namespace std;
int cx = 0, cy = 0;
double x =0, y=0, r = 5;
int main(){
ofstream myfile;
myfile.open("dingo.txt");
for(int g =0 ; g <= 360; g++)
//find x and y
//Get points of a circle.
x = cx + r * cos(g);
y = cy + r * sin(g);
//This is what pops up below:
//In function int main()':
//Error: name lookup of 'g' changed for ISO 'for' scoping [-fpermissive]
//note: (if you use '-fpermissive' G++ will accept your code)
//where should I enter the required option?
myfile << "X: " << x << "; Y: " << y <<endl;
myfile.close();
return 0;
}
回答1:
You can add more compiler flags under "Other Options"
in "Settings"
> "Compiler"
Although I think you should fix your code first. For example, std::sin
and std::cos
accepts radians, not degrees. You also need braces around your for
statement.
for(int g =0 ; g <= 360; g++) {
//code here.
}
回答2:
Don't use -fpermissive
.
It means "I really, really know what I'm doing here, so please shut up" and is never, ever a good beginner's option.
And in this case, "g++ will accept your code" means "g++ will not complain about your code, but the bugs will still be there, and you will waste many hours looking for them since the code compiled without so much as a warning".
Indenting your code properly exposes the problem:
int main(){
int cx = 0, cy = 0;
double x = 0, y = 0, r = 5;
ofstream myfile;
myfile.open("dingo.txt");
for(int g = 0 ; g <= 360; g++)
x = cx + r * cos(g);
y = cy + r * sin(g); // <--- Here it is.
myfile << "X: " << x << "; Y: " << y <<endl;
myfile.close();
return 0;
}
It's clear that the indicated line uses g
, which is the loop variable.
In olden times, the scope of a variable declared in a for
-loop was actually the scope enclosing the loop (the main
function, in your case).
This was later changed so the scope of a loop variable is limited to the inside of the loop, but since there is a lot of legacy code that relies on the old rules, compilers provide a way to enable the obsolete behaviour.
What you intended was probably this:
for(int g = 0; g <= 360; g++)
{
x = cx + r * cos(g);
y = cy + r * sin(g);
myfile << "X: " << x << "; Y: " << y <<endl;
}
(which is also wrong, because sin
and cos
use radians, not degrees - but I'll leave that problem as an exercise.)
来源:https://stackoverflow.com/questions/13024111/fpermissive-option-in-codeblocks-where-do-i-put-that-fpermissive-option