void CNodo::DrawWithAnArrow(System::Drawing::Graphics^g, CNodo nd){
g->DrawRectangle(System::Drawing::Pens::Black, posx, posy, lado, lado);
System::String ^cadena = contenido.ToString();
System::Drawing::Font ^f = gcnew System::Drawing::Font("Arial", 10);
g->DrawString(cadena, f, System::Drawing::Brushes::Black, posx + static_cast<int>(lado / 4), posy + static_cast<int>(lado / 5)); // warning is in this line
g->DrawLine(System::Drawing::Pens::Black, posx + lado, posy + (lado / 2), nd.getX(), nd.getY() + (lado / 2));
}
Greetings to everyone in this forum.
So. I receive a warning from the compiler indicating that there is a possible loss of data because there is a conversion from int to float.
I get confused because all the variables that are in my code are integers ( posx, posy and lado), where "lado" is equal to 20.
I even used a static_cast to prevent the warning, but it's still there.
If anyone can help me out with this problem, I'll really appreciate it
The Graphics.DrawString method takes two float values for the x and y parameters. Try this:
static_cast<float>(posx + (lado / 4))
Please note that the lado/4 expression might cause a precision loss.
Related
I'm trying to learn C from the C Programming Language book, in there, one of the exercises is to make a Fahrenheit to Celsius converter.
my code following the books style and instructions is:
#include <stdio.h>
int main() {
float fhr;
for (fhr = 0; fhr <= 300; fhr += 20)
printf("%3.1f %6.1f\n", fhr, (5.0/9.0)*(fhr-32));
}
It says in the book:
I just want to know if making a celsius variable and then calling it in the printf function as an argument is better or doing it this way is better, from both human readability and more importantly if it makes any difference to the compiler (I.e. makes the program run any faster or slower.)
Thanks.
Making a variable and then passing it to the printf would surely improve the readability.
From the compiler point of view there's no actual difference. It doesn't affect runtime performances in any way. This is especially true when it comes down to the internal optimizations the compiler carries out.
From a compiler standpoint it potentially does have an impact. Depending on the compiler, it might see that the variable is only used once and "inline" the value anyway. Many may not, which would cause a hit to the overall performance. That being said, the performance hit would be inconsequential.
As for readability, storing it as its own variable would be easier to look at, and maintain later. Although for a small program like this, the difference is also pretty inconsequential; however, it might start making a difference in larger programs, especially if the value is going to be used more than once.
#include <stdio.h>
int main()
{
float fhr;
for (fhr = 0; fhr <= 300; fhr += 20)
{
float celsius = (5.0/9.0)*(fhr-32);
printf("%3.1f %6.1f\n", fhr, celsius);
}
}
You might also want to consider using a function, to abstract out how this value is determined. Again, this does create a hit to performance, and isn't necessary for such a small program, but would provide access to a way to determine the value from more places in the program. This would mean you would not need to rely on passing the value around, or having the variable within scope:
float fahrenheit_to_celsius(float fhr)
{
return 5.0 / 9.0 * (fhr - 32)
}
int main()
{
float fhr;
for (fhr = 0; fhr <= 300; fhr += 20)
{
float celsius = fahrenheit_to_celsius(fhr);
printf("%3.1f %6.1f\n", fhr, celsius);
}
}
You can also use a function for it, it won't be slower, and it's way better for readability (in my opinion)!
#include <stdio.h>
double fhr_to_cls(double fhr)
{
return ((5.0 / 9.0) * ( fhr - 32));
}
int main()
{
double fhr;
for (fhr = 0; fhr <= 300; fhr += 20)
printf("%3.1f %6.1f\n", fhr, fhr_to_cls(fhr));
}
regarding:
for (fhr = 0; fhr <= 300; fhr += 20)
printf("%3.1f %6.1f\n", fhr, (5.0/9.0)*(fhr-32));
the 0 and 300 and 20 and 32 are all integers that the code is trying to stuff into a float
the 5.0and9/0aredoubles`
to correct all the above, Suggest:
for ( fhr = 0.0f; fhr <= 300.0f; fhr += 20.0f )
printf("%3.1f %6.1f\n", fhr, (5.0f / 9.0f )*(fhr-32.0f));
I hope this is not a banal question but I just can't find the problem in my code. I keep getting the error message "expression result unused" and "relational comparison result unused" when trying to compile my code.
The problem is with the following function:
bool is_inside(double x, double y){
if(sqrt(pow((x-0,5),2)+pow((y-0,5),2))<0,5){
return true;
}
return false;
}
which gets called in this function:
void estimate_func(unsigned long nsteps, unsigned long nstep_print){
unsigned long i;
unsigned long in_circle=0;
double x,y;
double curr_pi,curr_s;
for(i=0;i<nsteps;i++){
x=drand48();
y=drand48();
if(is_inside(x,y)){ // call!!!
in_circle++;
}
if(!(i%(nstep_print+1))){
curr_pi=(double) 4*(in_circle/(i+1));
curr_s=4*(sqrt((curr_pi/4)*(1-curr_pi/4)/(double)(i+1)));
printf("\t%lu\t%.6lf\t%.6lf\t%.6lf\n", i+1, curr_pi ,
curr_pi-M_PI, curr_s);
}
}
}
Has anyone an idea what I am doing wrong?
The problem is, essentially, that C source code is not locale-aware. Clearly, in your locale, the comma is used as the decimal separator, so you write ½ as 0,5. C doesn't do it that way. It always uses the period as the decimal separator, so ½ is always 0.5.
The comma does something different in C. It's actually a distinct operator known as the comma operator. It evaluates both its operands, discards the result of the first, and returns the result of the second. So, taking into account the operator precedence, what you currently have is seen by the compiler as:
if((sqrt(pow(((x-0),5),2)+pow(((y-0),5),2))<0),5){
which, evaulating the inner comma operators, gives:
if((sqrt(pow(5,2)+pow(5,2))<0),5){
and evaluating the outer comma operator reduces to:
if(5){
which the compiler can tell is trivially true, and is therefore warning you about it. The return false block will never be reached.
The correct way to write the code would be:
bool is_inside(double x, double y){
return (sqrt(pow((x - 0.5), 2) + pow((y - 0.5), 2)) < 0.5);
}
Notice that I have also elided the pointless if statement. This does exactly the same thing, and is easier to read. A comparison always returns either 1 (true) or 0 (false) in C, so its result can be used directly as a Boolean.
I've also added spaces, because let that code breathe!
What maybe you want to do is this:
bool is_inside(double x, double y){
if(sqrt(pow((x-0.5),2)+pow((y-0.5),2))<0.5){
return true;
}
return false;
}
Change the , to . if you want to represent floating point numbers (real numbers)
Just refactoring your code a little bit:
bool is_inside(double x, double y){
return sqrt(pow((x-0.5),2) + pow((y-0.5),2)) < 0.5); // changing , to .
}
void estimate_func(unsigned long nsteps, unsigned long nstep_print){
unsigned long i, in_circle=0;
double x, y, curr_pi, curr_s;
for(i = 0; i < nsteps; i++){
x = drand48();
y = drand48();
if(is_inside(x,y)) in_circle++;
if(!(i % (nstep_print + 1))){
curr_pi = (double) 4 * (in_circle / (i + 1));
curr_s = 4 * (sqrt((curr_pi / 4) * (1 - curr_pi / 4) / (double)(i + 1)));
printf("\t%lu\t%.6lf\t%.6lf\t%.6lf\n", i + 1, curr_pi ,
curr_pi - M_PI, curr_s);
}
}
}
Always try as much as possible to reduce the number of lines in your code. Beautiful code is short and concise. Check out these exercises http://divostar.com/learn-c
I made a simple program in C that finds if a number is prime. I am new to C and decided to try to use scanf instead of hardcoded numbers to check. When I run my code:
#include <stdio.h>
typedef int bool;
#define true 1
#define false 0
int main(){
//I am going to check if the "checking" variable is a prime
int checking;
scanf("%d",checking);
//"stopper" is where the for loop will stop
int stopper = checking**0.5 + 1;
//"found" will show if I have found something bad
bool found = false;
for (int i = 2; i < stopper; i++)
{
if (checking % i == 0){found = true; break;}
}
if (!found) {printf("it is prime");}
else {printf("it is not prime");}
}
when I try to compile this with TCC it gives the error (primes.c is the name of the document)
primes.c:12 error: pointer expected
I don't know how to fix this.
EDIT: I just made stopper = checking/2 and the program crashes
int stopper = checking**0.5 + 1;
line 12... what do you expect the ** operator to do?
A * typically performs a multiply, or dereferences a pointer.
The compiler could be interpreting it as follows:
int stopper = checking * (*0.5) + 1;
Of course, trying to dereference a float (*0.5) is bad / impossible, hence the error.
Did you mean:
instead of **, you meant * (multiply)
instead of ** (not a C operator), you meant pow() (raise to the power of)
You also need to be specific - even if you're an expert at precedance, the reader may not be, and you may well be wrong.
If you're not sure what's going on, use braces to be specific, which of the following do you mean?
int stopper = checking * (0.5 + 1);
int stopper = (checking * 0.5) + 1;
int stopper = pow(checking, 0.5) + 1;
int stopper = pow(checking, 0.5 + 1);
If you are indeed after the square root, then as #JeremyP says, invert your thinking - multiply is much less costly than pow():
for (int i = 2; i * i <= checking; i++)
You have two problems in your program:
(1) Replace
int stopper = checking**0.5 + 1;
with
int stopper = checking*0.5 + 1;
(2) Replace
scanf("%d",checking);
with
scanf("%d",&checking);
You should be good to after these corrections.
There's no built in operator to raise a number to the power of another number. There is a function to do that - also a square root function but you don't need them (see below).
x**y
is parsed as
x* (*y)
which is where your pointer error comes from
Instead of trying to find the square root, come at it from the other direction, change your for loop like this
for (int i = 2; i * i <= checking; i++)
Also, as others have said, the scanf is wrong.
scanf("%d",&checking);
// ^- scanf needs a pointer to an int.
Firstly, the scanf is wrong.
Use scanf("%d",&checking);
For finding the square root use math.h library for sqrt function.
int stopper = sqrt(checking) + 1;
There were a lot of typing mistakes in your code. Please, correct your syntax before asking a question.
Ideone link for code
Like I already wrote in the title I have the problem that I need to understand what double (f)(double) could mean in C. The whole methode header looks like this:
Bmp* drawGraph(double (f)(double),double minX,double maxX)
It's for a university project an my professor likes to be absent or not reachable through email or other ways of communication.
I think the name and so the propose of the methode is pretty much self-explaining.
In the letter of information to this method was said that "f" should be a function but I don't know what kind of parameter I should give the method in that case.
Bmp* drawGraph(double (f)(double),double minX,double maxX)
{
double height = f(maxX);
Bmp* bmp = newBmp(maxX, f(maxX) * 2);
background(bmp, BLACK);
//Hier zeichne ich das Koordinatensystem
//in seiner minimalistischten Form
drawLine(bmp, GREEN, 0, f(maxX), maxX, f(maxX));
drawLine(bmp, GREEN, 0, 0, 0, f(maxX) * 2);
for(double d = minX; d < maxX; d += 0.1)
{
drawLine(bmp, RED, d, f(d) + height, d + 0.1, f(d + 0.1) + height);
}
return bmp;
}
double (f)(double)
f is a parameter of function type: a function that has a double parameter and that returns a double value.
For example:
double foo(double a)
{
return a + 42.0;
}
The parameter is adjusted (and therefore the declaration is equivalent) to a pointer to a function that has a double parameter and that returns a double value.
double (*f)(double)
So these declarations are all equivalent:
void bla(double (f)(double));
void bla(double f(double));
void bla(double (*f)(double));
I am pretty flabbergasted as to why my code got stuck at the 16512th iteration even though it seemed to have no syntactical problems. Here is the code:
#include <stdio.h>
/*C version of Newton-Raphson method*/
float sqrt(float num);
main()
{
int i;
for (i = 1; i <= 100000; i++) {
printf("%d: %.3f\n", i, sqrt(i));
}
}
float sqrt(float num)
{
float guess, e, upperbound;
guess = 1;
e = 0.001;
do
{
upperbound = num / guess;
guess = (upperbound + guess) / 2;
} while (!(guess * guess >= num - e &&
guess * guess <= num + e));
return guess;
}
The code is supposed to find the square-root of all numbers from 1 to 100000 using the Newtonian-Raphson method, but nothing happened after the 16152th iteration. I am using the Developer Command Prompt for VS2012 to compile my scripts, if that information is of any help. Enlightenment will be gladly appreciated.
Honestly, when I posted mycomment, it was more a hunch than real knowledge. The algorithm was valid, so something must be making the while loop not terminate, and since you were properly using epsilons, we were hitting the limits from the float.
#PaulR's comments make it make more sense. The sqrt of 16512 is 128.499027233672... Float has fairly limited precision, so it wasn't getting anything within .001 of that number. It makes even more sense if you think of an even bigger number, e.g. sqrt(123455555.54321) (which is 11111.11111). Floating point precision won't necessarily even get you to the 11111, let alone 11111.111.
Changing to double "fixes" this, but just kicks the can down the road. Somewhere later on, we'd have the same precision issue, and this algorithm should work on any size number.
#mrbratch brings up the robust solution - define your tolerance as a percentage of the number. If you set e = num * 0.00001, your loop will always complete. Obviously, you can play with epsilon and tweak it to your satisfaction. And note, for big numbers, this can give you an integer that's not even the closest int to the right answer.
I can't speak for python, but I can confirm that javascript uses double precision.
As already explained in the comments, the problem is because you can't have that much precision (0.001) with any number. In particular, when the number is large enough, only the most important digits are saved. See the IEEE 754 standard if you want more information about how it works. http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
Now, I'd recommend that you use a percentage of error for the tolerance:
float sqrt(float num)
{
float guess, e, upperbound;
guess = 1;
e = 0.001;
do
{
upperbound = num / guess;
guess = (upperbound + guess) / 2;
} while (!(guess * guess / num >= 1 - e &&
guess * guess / num <= 1 + e));
return guess;
}
Simple adjustment
Use relative Floating Point precision, not absolute.
There area as many FP representable numbers between 0.001 and 0.002 as between 1,000 and 2,000. So when calculating square root, the iterations should depend on the local relative error.
Do not use absolute error bounds like e = 0.001, but relative ones. Code then runs just fine.
// e = 0.001;
e = 0.001 * num;
[edit] I know see #Scott Mermelstein has a similar comment.
IMHO, the squaring causes loss of precision:
#include <stdio.h>
/*C version of Newton-Raphson method*/
float mysqrt(float num); /* avoid conflicts with built-in sqrt() if any */
int main(void)
{
int i;
for (i = 1; i <= 100000; i++) {
printf("%d: %.3f\n", i, (double)mysqrt(i)); /* cast to double, since printf() is varargs */
}
return 0;
}
float mysqrt(float num)
{
float newguess, e, oldguess;
e = 0.001;
newguess = 1.0;
do
{
oldguess = newguess;
newguess = (num/oldguess + newguess ) / 2;
/* compare tor the previous value; avoid squaring */
} while (newguess / oldguess > (1+e) || oldguess / newguess > (1+e) );
// } while (newguess < oldguess -e || newguess > oldguess +e); // "mostly works"
return newguess;
}