Click here to Skip to main content
15,896,557 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm new to C, and I challanged myself to make an angle calculator in function of Vo, G, target X and target Y, yet I'm struggling with the simplest part of it, to convert a floating number into it's negative. I made a separate project in code blocks and have summarized my problem into a simpler code, take a look:

What I have tried:

C
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
    float V,Vi;
    char v;
    if(v=='-'){
        V=0-Vi;
    }else{
    V=Vi;
    }
        printf("Projectile initial velocity is + or -?\n");
        scanf(" %c", &v);
    printf("Projectile initial velocity module?\n");
        scanf("%lf", &Vi);
        printf("%f", V);
    return 0;
}


//This has an output of 1.875000 (??)
Posted
Updated 19-Jun-22 13:22pm
v2

Generally speaking, for any language, multiplying by -1.0 changes the sign of a number, either integer or floating point.

I'm going to guess that something went wrong when you posted your code, since what you have here does some calculations with uninitialized data, prompts for values, then exits, which is guaranteed to give unexpected results. I also notice
C
float Vi;
scanf("%lf", &Vi);
The format specifier %lf tells scanf() to expect a pointer to a double (i.e. long float), but in this case Vi is a float. So again, its unknown what value Vi will ultimately get. It might be the value expect, it might be zero, or it might be some other, seemingly random value. Depending on the compiler you're using, turning on compiler warnings should catch that mistake.
 
Share this answer
 
Comments
merano99 18-Jun-22 2:43am    
All correct. It should be added that it is not good to name all variables V, moreover in upper and lower case.
A char is usually written with the variable name c. (+5)
Quote:
I'm struggling with the simplest part of it, to convert a floating number into it's negative.


You mean make a positive float number negative?

C
float V, Vi;

V = 1;
Vi = -V;
 
Share this answer
 
Ok, so i had a brak and came back, after reading some solutions I've came um with this:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    float V,Vi;
    char opV;

    scanf(" %c", &opV);
    scanf("%fl", &Vi);
        if(opV=='-'){
        V = 0 - Vi ;
    }else{V=Vi;};
    printf("%f\n", V);
    return 0;
}
 
Share this answer
 
Your coded logic is absolutely wrong. If you step through your code in debugger you will quickly figure this out
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900