How to convert and print given kelvin value to celsius on another label in objective c - objective-c

On a webservice program,i fetched temperature value from an API and its in kelvin value....i want to convert that to celsius and print to another label in same page along with that kevin value... As a beginner i don't know much how to do..please help
lbl1.text=[dic retrieveForPath:#"current.city.#name"];
lbl2.text=[dic retrieveForPath:#"current.city.coord.#lon"];
lbl3.text=[dic retrieveForPath:#"current.temperature.#value"];
here on 'lbl3 ,i printed temperature in kelvin.....and how to convert and print that to another label by doing this equation T(°C) = T(K) - 273.15

Assuming that you have a lbl4 object, this will display the data with 2 decimal places, e.g. 12.51C
float centigrade = [[dic retrieveForPath:#"current.temperature.#value"] floatValue] - 273.15;
lbl4.text = [NSString stringWithFormat:#"%.2fC", centigrade];

Related

convert centimeter to feet and inches and vice versa different output?

I am using following code to convert centimeters into feet and inches but it doesn't work as expected.
+ (NSString*)getfeetAndInches:(float)centimeter {
float totalHeight = centimeter * 0.032808;
float myFeet = (int)totalHeight; //returns 5 feet
float myInches = fabsf((totalHeight - myFeet) * 12);
NSLog(#"%f",myInches);
return [NSString stringWithFormat:#"%d' %0.0f\"",(int)myFeet,roundf(myInches)];
}
I'm using the following code to convert feet and inches string into centimeter
NSInteger totalInches = ([self.Feets integerValue] * 12) + [self.Inches integerValue];
self.heightInCm = totalInches * 2.54;
But when I convert self.heightInCm back to feet and inches it does not provide correct value.Could someone post a perfect working example of this
In general, your code works correctly. There are some minor issues, e.g. the fabsf is not necessary but from my testing it works well.
The problem you have is probably caused by the fact, that when converting to feets and inches, you are rounding off values.
An inch is equal to 2.54 cm. If you are rounding inches to an integer value, your maximum precision will be 2.54 cm.
For example, 5'11' is 180,3 cm. 6'0 is 182,8cm. Anything between those two values (e.g. 181, 182, 183 will get rounded to either 5'11 or 6'0).
The correct solution depends on your use case. If you are only presenting the values to the user, keep them in centimeters and only convert to feet&inches when displaying. If your users are entering the value, you can't make it more precise but you can accept/display inches as a decimal value (replace roundf(myInches) with just myInches and use [self.inches floatValue]).
From the comments, you also have a rounding problem when inches calculated as 11.8 are rounded up to 12 which doesn't make sense in the result. I recommend to rework the algorithm into the following:
const float INCH_IN_CM = 2.54;
NSInteger numInches = (NSInteger) roundf(centimeter / INCH_IN_CM);
NSInteger feet = numInches / 12;
NSInteger inches = numInches % 12;
return [NSString stringWithFormat:#"%#' %#\"", #(feet), #(inches)];
That will easily solve the 12 inch problem because the round is applied to the total length in inches.
This is the Swift version, to convert centimeters to feet and inches:
SWIFT 4
func showFootAndInchesFromCm(_ cms: Double) -> String {
let feet = cms * 0.0328084
let feetShow = Int(floor(feet))
let feetRest: Double = ((feet * 100).truncatingRemainder(dividingBy: 100) / 100)
let inches = Int(floor(feetRest * 12))
return "\(feetShow)' \(inches)\""
}

Having trouble creating a weather converter program

I started school for computer programming just a couple weeks ago and we just started Objective-C! We need to convert Celsius to Fahrenheit and Kelvin. To do that I must input the amount of Celsius. Then I use this equation to get Fahrenheit: * 9 / 5 + 32. To get Kelvin I add 273.15.
#include <stdio.h>
int main(void)
{
float Celsius;
float Farenheight = Celsius * 9 / 5 + 32;
float Kelvin = Celsius + 273.15;
printf("How many degrees in Celsius?");
scanf("%s %s %d", Celsius, Farenheight, Kelvin);
printf("C: %s, F: %s, K: %d", Celsius, Farenheight, Kelvin);
}
This is (the second revision of) what I came up with so far, but I am really unsure on how to do this. If anyone can help me that would be great!
Funnily enough, temperature conversion came up in another context earlier today.
Adapting that code to your outline, you need to read the value in celsius before you convert anything to kelvin or fahrenheit (whereas your code converts an uninitialized value, which is not a good idea):
double celsius;
printf("What is the temperature in degrees Celsius? ");
if (scanf("%lf", &celsius) == 1)
{
double kelvin = celsius + 273.15;
double fahrenheit = (celsius + 40.0) * (9.0 / 5.0) - 40.0;
printf("%7.2f °C = %7.2f K = %7.2f °F\n", celsius, kelvin, fahrenheit);
}
Note that the input is checked for validity before the result is used.
The conversion formula is simpler than the usual one you see quoted, and is symmetric for converting °F to °C or vice versa, the difference being the conversion factor (9.0 / 5.0) vs (5.0 / 9.0). It relies on -40°C = -40°F. Try it:
C =  0°C; (C+40) = 40; (C+40)*9 = 360; (C+40)*9/5 = 72; (C+40)*9/5-40 = 32°F.
F = 32°F; (F+40) = 72; (F+40)*5 = 360; (F+40)*5/9 = 40; (F+40)*5/9-40 =  0°C.
Absolute zero is -273.15°C, 0K, -459.67°F.
Use this code snippet to read input from stdin:
#include <stdio.h>
int main (int argc, char *argv[]) {
int celsius;
printf("What is the temperature in celsius? ");
scanf("%d", &celsius);
printf("celsius degree = %d\n", celsius);
}

Code Implementation of Formula to get a MidPoint Coords between to GPS Positions not working correctly

Good day, I'm fairly new to Objective C Dev and am enquiring to an implementation of the midpoint formula located here http://www.movable-type.co.uk/scripts/latlong.html.
Formula:
Bx = cos(lat2).cos(Δlong)
By = cos(lat2).sin(Δlong)
latm = atan2(sin(lat1) + sin(lat2), √((cos(lat1)+Bx)² + By²))
lonm = lon1 + atan2(By, cos(lat1)+Bx)
My Implementation of this formula in Objective C is.
- (CLLocationCoordinate2D) getMidPointCoords
{
double dLon = (self.toCoordinate.longitude - self.fromCoordinate.longitude) * (M_PI/180);
double Bx = cos(self.toCoordinate.latitude)*cos(dLon);
double By = cos(self.toCoordinate.latitude)*sin(dLon);
double latM = atan2(sin(self.fromCoordinate.latitude)+sin(self.toCoordinate.latitude), sqrt( (cos(self.fromCoordinate.latitude)+Bx)*(cos(self.fromCoordinate.latitude)+Bx) + By*By) );
double lonM = self.fromCoordinate.longitude + atan2(By, cos(self.fromCoordinate.latitude) + Bx);
CLLocationCoordinate2D midPoint;
midPoint.latitude = latM;
midPoint.longitude = lonM;
}
When I debug this code though it is clearly returning the incorrect coordinates.
So essentially my Question is "Is this because of the fact that I am using doubles?" or is my implementation of this formula simply flauwed?
Thank you in advance to any assistance, or insight provided.
The trigonometric functions you are using (sin, cos, atan2) require their parameter to be in radians, not degrees.
For example, in this line:
double Bx = cos(self.toCoordinate.latitude)*cos(dLon);
the cos(self.toCoordinate.latitude) is wrong because self.toCoordinate.latitude is in degrees but cos requires radians.
Everywhere that you call a trigonometric function, first convert the parameter from degrees to radians (multiply degrees by (M_PI/180.0)).
In addition, in this line:
double lonM = self.fromCoordinate.longitude + atan2(...
the self.fromCoordinate.longitude also needs to be converted to radians because the rest of the expression is also in radians.
Finally, at the end latM and lonM will have the midpoint but in radians (not degrees).
So when setting midPoint.latitude and midPoint.longitude, you have to convert latM and lonM from radians back to degrees by multiplying them by (180.0/M_PI).

Rounding a float number in objective-c

I want to know if there is a simple function that I can use such this sample.
I have a
float value = 1.12345;
I want to round it with calling something like
float value2 = [roundFloat value:value decimal:3];
NSLog(#"value2 = %f", value2);
And I get "1.123"
Is there any Library or default function for that or I should write a code block for this type of calculations?
thank for your help in advance
Using NSLog(#"%f", theFloat) always outputs six decimals, for example:
float theFloat = 1;
NSLog(#"%f",theFloat);
Output:
1.000000
In other words, you will never get 1.123 by using NSLog(#"%f", theFloat).
Cut-off after three decimals:
float theFloat = 1.23456;
float newFLoat = (int)(theFloat * 1000.0) / 1000.0;
NSLog(#"%f",newFLoat);
Output:
1.234000
Round to three decimals (using roundf() / lroundf() / ceil() / floor()):
float theFloat = 1.23456;
float newFLoat = (int)(roundf(theFloat * 1000.0)) / 1000.0;
NSLog(#"%f",newFLoat);
Output:
1.235000
Round to three decimals (dirty way):
float theFloat = 1.23456;
NSString *theString = [NSString stringWithFormat:#"%.3f", theFloat];
float newFloat = [theString floatValue];
NSLog(#"%#",theString);
NSLog(#"%f",newFloat);
Output:
1.235
1.235000
For printing the value use:
NSLog(#"value2 = %.3f", value2);
Rounding to 3 decimal digits before calculations doesn't really make sense because float is not a precise number. Even if you round it to 1.123, it will be something like 1.122999999998.
Rules:
Usually you round up only to print the result - string formatter can handle it (see above).
For precise calculations (e.g. currency), don't use floating point, use NSDecimalNumber or fixed point arithmetics.
Floating point numbers don't have decimal places, they have binary places. Decimal-radix numbers have decimal places. You can't round floating point numbers to specific numbers of decimal places unless you convert to a decimal radix. No routine, method, function etc., that returns a floating point value can possibly carry out this task.
Note that "Round" is not necessarily as simple a topic as you think. For example
DIY Calculator: Rounding Algorithms 101 lists 16 different methods for rounding a number.
Wikipedia:Rounding covers a lot of the same ground
And Cplusplus has source code for a bunch of Rounding Algorithms that are easy translatable to objective-c
How you want to round will depend on the context of what you are doing with for data.
And I should point out that Stack Overflow already has a plethora of other questions about rounding in objective-c
//Your Number to Round (can be predefined or whatever you need it to be)
float numberToRound = 1.12345;
float min = ([ [[NSString alloc]initWithFormat:#"%.0f",numberToRound] floatValue]);
float max = min + 1;
float maxdif = max - numberToRound;
if (maxdif > .5) {
numberToRound = min;
}else{
numberToRound = max;
}
//numberToRound will now equal it's closest whole number (in this case, it's 1)
Here is a simple way to do it:
float numberToRound = 1.12345f;
float remainder = numberToRound*1000.0f - (float)((int)(numberToRound*1000.0f));
if (remainder >= 0.5f) {
numberToRound = (float)((int)(numberToRound*1000.0f) + 1)/1000.0f;
}
else {
numberToRound = (float)((int)(numberToRound*1000.0f))/1000.0f;
}
For an arbitrary decimal place, substitute 1000.0f in the above code with
float mult = powf(10.0f, decimal);
try
#import <math.h>
float cutFloat( float number, int decimal) {
number = number*( pow(10,decimal) );
number = (int)number;
number = number/( pow(10,decimal) ) ;
return number;
}

How do I display a full 360 degrees using Actionscript 2 and Trigonometry?

I'm creating a game that uses trigonometry to calculate and display distance and degrees in dynamic text boxes. I'm calculating the distance of my cursor from center of a movie clip. And using that center of the movie clip, I'm trying to calculate and display a full 360º as my cursor moves around the swf. I have the distance part of the game working but the part that displays degrees is not working properly. The dynamic text box only display from 90º thru 270º. Instead of going past 270º to 360º/0º to 90º, it just counts back down from 270º to 90º. Below is my actionscript. I'd greatly appreciate any help or suggestions. Thanks!
//Mouse and Dynamic Text Boxes-------------------------
Mouse.hide();
onMouseMove = function () {
feedback.text = "You are moving your mouse";
cursor._x = _xmouse;
cursor._y = _ymouse;
updateAfterEvent();
xmouse_value.text = Math.atan2((a), (b));
ymouse_value.text = Math.round(radians*180/Math.PI)
updateAfterEvent();
};
Mouse.addListener(myListener);
//distance (RANGE)
_root.onEnterFrame = function () {
xmid = Stage.width/2;
ymid = Stage.height/2;
a = _root._ymouse-ymid;
b = _root._xmouse-xmid;
c = Math.sqrt(Math.pow(a, 2)+Math.pow(b, 2));
feedbacka.text = Math.round(a);
feedbackb.text = Math.round(b);
feedbackc.text = Math.round(c/30.4);
updateAfterEvent();
var radians:Number;
var degrees:Number;
//Calculcate Radians
//Radians specify an angle by measuring the length around the path of the circle.
radians = Math.atan2((c), (b))
//calculate degrees
//the angle the circle is in relation to the center point
//update text box inside circle
radians_txt = Math.round(radians*360/Math.PI);
degrees_txt = Math.round(radians*180/Math.PI);
updateAfterEvent();
//getting past 270 degrees
radians2_txt = Math.round(radians/Math.PI);
radians2_txt = Math.floor(radians + -270);
}
The parameters to atan2 should be the delta-y and delta-x between the two points, but you are passing the distance between the two points and the delta-x. Try this instead:
radians = Math.atan2(a, b);
The next problem is to convert the radians into degrees. To convert radians to degrees, you can do this:
degrees_txt = radians * 180 / Math.PI;
Note that atan2 returns from between -Math.PI / 2 to Math.PI / 2. When converted to degrees, this range becomes -180 to 180. To convert to 0 to 360, you can add 360 to the result if it is negative:
if(degrees_txt < 0) degrees_txt += 360;