Jump to content
xisto Community
htdefiant

Absolute Value In C

Recommended Posts

Hey,
I'm writing a program for a friend in Calculus. The goal is for him to be able to input a number, and have the computer return whether it is positive or negative, and its absolute value. Here is what I have so far:

     printf("Please enter a number linenums:0'>/* positive.cpp* The program that gets a number and checks if it is a positive number.*It prints an appropriate message indicating if its positive or negative and also prints the*absolute value of the number.*/#include <stdio.h>#include "genlib.h"#include "simpio.h"main (){     int num1;     bool positive;     printf("This program will determine if the user inputted number is positive or negative. \n");     printf("It will also display the number's absolute value. \n");     printf("Please enter a number: \n");     num1=GetInteger ();     if (num1==0)        printf("The number %d is neither positive nor negative. \n", num1);else      if (num1>0)        {                printf("The number %d is positive and its absolute value is %d. \n", num1, num1);                positive=true;                }                else          {             printf("The number %d is negative and its absolute value is %d. \n", num1, num1);             positive=false;             }        getchar ();        return 0;        }
Obviously the line
printf("The number %d is negative and its absolute value is %d. \n", num1, num1);
is flawed. How do I fix it so if the number is negative it will display the correct absolute value?

Thank you.

Share this post


Link to post
Share on other sites

The correct syntax for that line would be:printf("The number %d is negative and its absolute value is %d. \n", num1, abs(num1));also if you wanted to get the absolute value of a floating point number instead you can use fabs(variable).

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.