Print negative as zero

This is a discussion on Print negative as zero within the C Programming forums, part of the General Programming Boards category; Code: #include <stdio.h> #define GRAVITY 16 int main(void) { int time, altitude, new_alt; time=1; printf("What is the altitude you are ...

  1. #1
    Registered User
    Join Date
    Feb 2006
    Posts
    2

    Print negative as zero

    Code:
    #include <stdio.h>
    
    #define GRAVITY 16
    
    int main(void) {
    
    	int time, altitude, new_alt;
     	
    	time=1;
    	
    	printf("What is the altitude you are dropping your object from?\n");
    	scanf("%d", &altitude);
    	
    	printf("Time	Altitude\n");
    		
    	// Loop until altitude reaches zero.
      while (new_alt >= 0) {
    
        // Calculate the new altitude.
        new_alt = altitude-GRAVITY*time*time;
    
        
    	 
    	 // Print out the table of time and altitude.
      	 printf("%d		%d\n", time,new_alt);
    		
        time++; // Go to the next time value.
    
      }
      	
    
      
    
      return 0;


    the last one prints 3 seconds -24 altitude. i need all values below 0 to print as 0. How do I do that?

  2. #2
    Mad OnionKnight's Avatar
    Join Date
    Jan 2005
    Location
    Umeň, Sweden
    Posts
    555
    So, if a value is less than 0 you want it the result to equal 0?

  3. #3
    Registered User
    Join Date
    Feb 2006
    Posts
    2
    yes.
    im pretty sure it has something to do with an if statement but i dont know where to put it.

  4. #4
    Mad OnionKnight's Avatar
    Join Date
    Jan 2005
    Location
    Umeň, Sweden
    Posts
    555
    Before the printf, put
    Code:
    if (new_alt < 0)
        new_alt = 0;

  5. #5
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,255
    Or if you don't want to change the value of new_alt.
    Code:
    printf("new_alt = %d\n",(new_alt > 0) ? new_alt : 0);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. merging linked lists
    By scwizzo in forum C++ Programming
    Replies: 15
    Last Post: 09-14-2008, 06:07 PM
  2. Personal Program that is making me go wtf?
    By Submeg in forum C Programming
    Replies: 20
    Last Post: 06-27-2006, 01:13 AM
  3. Scope And Parameter Passing
    By djwicks in forum C Programming
    Replies: 6
    Last Post: 03-28-2005, 08:26 PM
  4. how to handle integer overflow in C
    By kate1234 in forum C Programming
    Replies: 8
    Last Post: 04-23-2003, 01:20 PM
  5. What kind of programs should I start writing?
    By Macabre in forum C++ Programming
    Replies: 23
    Last Post: 04-12-2003, 09:13 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21