Unable to do calculation and get print out to label - iphone

I'm doing the following code when they hit the calculate button in my app:
float sqft = ([textfield1.text floatValue]);
float thick= ([textfield2.text floatValue]);
float cos = ([textfield3.text floatValue]);
float eff = ([textfield4.text floatValue]);
float num = ((thick*.5)*sqft)/eff;
float cost = (num*cos);
float costft = (cost/sqft);
label1.text = [NSString stringWithFormat:#"%2.f",num];
label2.text = [NSString stringWithFormat:#"%2.f",cost];
label3.text = [NSString stringWithFormat:#"%2.f",costft];
When I do this the labels only return zeros. I have set the labels to maually be strings just to see if it was a delegation thing but I can't figure out why my formulas return zeros only

The problem is with the way you have used %2.f in your code,
%2.f gives you the rounded value of the answer in 2 number format. If any of your answer is less than or equals to 0.5 . then you get 0 as the answer.
now it should work
float sqft = ([textfield1.text floatValue]);
float thick= ([textfield2.text floatValue]);
float cos = ([textfield3.text floatValue]);
float eff = ([textfield4.text floatValue]);
float num = ((thick*.5)*sqft)/eff;
float cost = (num*cos);
float costft = (cost/sqft);
label1.text = [NSString stringWithFormat:#"%2f",num];
label2.text = [NSString stringWithFormat:#"%2f",cost];
label3.text = [NSString stringWithFormat:#"%2f",costft];

Its working proper at my end . But in one case you will get ZERO value when your value is 0.786676 like that..
textfield1.text = #"123.89";
textfield2.text= #"123.00";
textfield3.text= #"123.7";
textfield4.text= #"123";
float sqft = ([textfield1.text floatValue]);
float thick= ([textfield2.text floatValue]);
float cos = ([textfield3.text floatValue]);
float eff = ([textfield4.text floatValue]);
float num = ((thick*.5)*sqft)/eff;
float cost = (num*cos);
float costft = (cost/sqft);
NSLog(#"Num : %#",[NSString stringWithFormat:#"%2.f",num]);
NSLog(#"Cost : %#",[NSString stringWithFormat:#"%2.f",cost]);
NSLog(#"Costft : %#",[NSString stringWithFormat:#"%2.f",costft]);
Output
Num : 62
Cost : 7663
Costft : 62

You want to limit the digits after the decimal point to two - that is why you are using .2f, right? If so, you should use this #"%.2f"
Just try this:
label1.text = [NSString stringWithFormat:#"%.2f",num];
label2.text = [NSString stringWithFormat:#"%.2f",cost];
label3.text = [NSString stringWithFormat:#"%.2f",costft];

Related

how to calculate rise over run value by given angle with iPhone device

hello i am calculating the device angle by fallowing code and then converting this angle to rise over run formula i am getting the wrong pitch value but when i start rotating device(left to right and right to left in landscape mode) then after some time i started to get correct pitch value here is my code....
operationQueue = [[NSOperationQueue alloc] init];
motionManager = [[CMMotionManager alloc] init];
motionManager.deviceMotionUpdateInterval = 2.0 / 60.0;
[motionManager startDeviceMotionUpdates];
[motionManager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXArbitraryZVertical toQueue:operationQueue
withHandler:^(CMDeviceMotion *motion, NSError *error)
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
CGFloat x = motion.gravity.x;
CGFloat y = motion.gravity.y;
CGFloat z = motion.gravity.z;
CGFloat angle = atan2(y, x) + M_PI_2; // in radians
CGFloat angleDegrees = angle * 180.0f / M_PI; // in degrees
CGFloat r = sqrtf(x*x + y*y + z*z);
CMQuaternion quat = motionManager.deviceMotion.attitude.quaternion;
NSNumber *myroll = [NSNumber numberWithInt:radiansToDegrees(atan2(2*(quat.y*quat.w - quat.x*quat.z), 1 - 2*quat.y*quat.y - 2*quat.z*quat.z))];
NSNumber *mypitch = [NSNumber numberWithInt:radiansToDegrees(atan2(2*(quat.x*quat.w + quat.y*quat.z), 1 - 2*quat.x*quat.x - 2*quat.z*quat.z))];
NSNumber *myyaw = [NSNumber numberWithInt:radiansToDegrees(2*(quat.x*quat.y + quat.w*quat.z))];
//double actualYaw = [myyaw doubleValue];
// CGFloat tiltForwardBackward = ceilf(motionManager.deviceMotion.attitude.yaw * 180 / M_PI);
**strong text**float pitchValue = motionManager.deviceMotion.attitude.pitch;
pitchValue = [mypitch doubleValue];
pitchValue = (pitchValue < 0) ? -(pitchValue) : pitchValue;
float pitchAngle = [mypitch doubleValue];
pitchAngle = (pitchAngle < 0) ? -(pitchAngle) : pitchAngle;
//pitchValue = (tan(pitchValue*(M_PI/180))*12);
**strong text**pitchValue = (tan((pitchValue*M_PI)/180))*12; // i am using this formula to calculate roof pitch value.
pitchValue = (pitchValue < 0) ? -(pitchValue) : pitchValue;
if(pitchValue >= 99.9){
pitchValue = 99.9;
}
deviceAngle.text = [NSString stringWithFormat: #"Pitch Value = %0.1f/12, Pitch Angle = %.2f", pitchValue, pitchAngle];
//deviceAngle.text = [NSString stringWithFormat: #" %.1f/12",pitchValue];
}];
}];
please help is there any way to calculate rise over run value by using any of this three value.i am keeping my iPhone in landscape mode and then rotating left to right and right to left.
am using wrong value?.i am interested to calculate roof pitch value.is there any formula?.
please help me thanks in advance.

Conversion Fahrenheit to celsius programmatically

In my project, want to show the weather in fahrenheit first, then if the user wants clickes on conversion, needs to show the weather in celsius. My code is
NSNumber *metric = [[NSUserDefaults standardUserDefaults] objectForKey:#"metric"];
NSLog(#"Metric is %#", metric);
CGFloat aFloat = [speed floatValue];
CGFloat tFloat = [temperature floatValue];
CGFloat tempFloat = (tFloat-30)/2;
NSNumber * p_Number = [NSNumber numberWithFloat:tempFloat];
//Convert mph to kmph
if ([metric boolValue]) {
[windValueLabel setText:[NSString stringWithFormat:#"%.2f kmph", aFloat * 1.6] ];
temperatureLabel.text = [NSString stringWithFormat:#"%#", p_Number];
}
else{
[windValueLabel setText:[NSString stringWithFormat:#"%.2f mph", aFloat / 1.6]];
temperatureLabel.text = [NSString stringWithFormat:#"%#", temperature];
}
When u start the app, its working and showing temperature in fahrenheit, but crashes at celsius man... is that the current conversion. help me out guys
Your formula is slightly off, you want:
CGFloat tempFloat = (tFloat-32.0) / 1.8;
But that's not what making it crash. In fact, it's not crashing for me. What message do you get when it crashes?

Get Percentage from two integers

I am almost half way there to getting the percentage of two integers i just need help with the final hurdle, here is my coding so far below it works but sometimes its like yes = 50 and no = 20% when it should be 50/50.
int yes;
int no;
//Work out percentages
if ([VotedAnswer.text isEqualToString:#"No"]){
yes = [currentYes intValue];
no = [currentNo intValue] + 1;
}else{
yes = [currentYes intValue] + 1;
no = [currentNo intValue];
}
int total = yes + no + 1;
int pcntYes = (yes *100) / total;
int pcntNo = (no *100) / total;
float barNo = pcntNo / 100.0f;
float barYes = pcntYes / 100.0f;
//Set percent labels
yesPercent.text = [NSString stringWithFormat:#"%d%%", pcntYes];
noPercent.text = [NSString stringWithFormat:#"%d%%", pcntNo];
//Set Percent Bars
YesProgress.progress = barYes;
NoProgress.progress = barNo;
You should not be adding 1 to total. The total number of votes cast is simply yes + no.
Oh and don't forget to update currentYes and currentNo you haven't shown code that is doing that.
It works for me
int yes = [cell.yesAnswer.text intValue] ;
int no = [cell.noAnswer.text intValue];
int total = yes + no + 1;
int pcntYes = (yes *100) / total;
int pcntNo = (no *100) / total;
float barNo = pcntNo / 100.0f;
float barYes = pcntYes / 100.0f;
cell. yesProcent.text = [NSString stringWithFormat:#"%d%%", pcntYes];
cell. noProcent.text = [NSString stringWithFormat:#"%d%%", pcntNo];

How to use a segment to select a value then use that value in a formula

I am trying to simply have a segment when selected pick a factor and use it in a formula. The problem i am having is converting the factor a (float) into a value a (double) and show this on the display. What am I doing wrong here? Seems like an easy fix but I've tried a lot of things to no avail.
.h
NSInteger segPicked, var1, var2;
.m
var1 = 1100;
var2 = 2.5;
- (void) pickOne:(id)sender { // Selector for twosegment controller
if (checkCondition == properCondition) {
segUnit.text = [twoSegments titleForSegmentAtIndex: [SixSegments selectedSegmentIndex]];
segPicked = [twoSegments selectedSegmentIndex];
float factor = 0;
if (segPicked == 0 ) {
factor = 0.28;
} else if (segPicked == 1 ) {
factor = 0.16;
}
double value = (factor*(var1/var2)); <--- It crashes here..
Result.text = [NSString stringWithFormat:#"Segment with = ", value];
}
}
check that var2 must be != 0
and:
Result.text = [NSString stringWithFormat:#"Segment with = ", value];
should be:
Result.text = [NSString stringWithFormat:#"Segment with = %f", value];
EDIT:
float factor;
NSInteger var1;
NSInteger var2;
float var2_test;
var1 = 1100;
var2 = 2.5;
var2_test = 2.5;
NSLog(#"int var2: %i, float var2_test: %f", var2, var2_test); // var2=2
factor = 0.16;
double value;
value = (factor*(var1/var2)); // Not Crashes to me!
NSLog(#"******: %f", value);
it all works good to me, no crashes, are you sure it crashes at that point?
just a consideration:
var2 = 2.5;
var2 is: 2 (it's an integer)
Division by Zero ?
Dividing two integers?
double value = (factor*(var1/var2));

OBJ-C: Getting the minimum/maximum value in a NSMutableArray

I want to get the maximum and minimum values of a NSMutableArray so I can create a core-plot plotspace and graph based around those max and min values.
My code is as follows:
NSMutableArray *contentArray = [NSMutableArray arrayWithCapacity:100];
NSUInteger i;
for (i=0; i<60; i++){
id x = [NSNumber numberWithFloat:i*0.05];
id y = [NSNumber numberWithFloat:1.2*rand()/(float)RAND_Max + 0.6];
[contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:x, #"x", y, #"y", nil]];
}
self.dataForPlot = contentArray;
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat() length:CPDecimalFromFloat()];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat() length:CPDecimalFromFloat()];
What do I fill in the blanks for xRange and yRange assignment if I want the graph to span only the space of what's specified in contentArray?
In this case, you should use -[CPPlotSpace scaleToFitPlots:]. For more general calculations on array values, read on...
This is an ideal use for Key-Value coding and associated array operators. In your example,
float maxX = [[contentArray valueForKeyPath:#"#max.x"] floatValue];
float minY = [[contentArray valueForKeyPath:#"#min.x"] floatValue];
float maxY = [[contentArray valueForKeyPath:#"#max.y"] floatValue];
float minY = [[contentArray valueForKeyPath:#"#min.y"] floatValue];
The array operators call valueForKeyPath: on the contentArray which gives an array built by calling the same valueForKeyPath: on each member of the array with the key path to the right of the array operator (i.e. #min and #max). The orignal call then applies the given operator to the resulting array. You could easily define a category on NSArray to give you back a struct of min/max values:
typedef struct {
float minX;
float minY;
float maxX;
float maxY;
} ArrayValueSpace;
#implementation NSArray (PlotSpaceAdditions)
- (ArrayValueSpace)psa_arrayValueSpace {
ArrayValueSpace result;
result.maxX = [[contentArray valueForKeyPath:#"#max.x"] floatValue];
result.minX = [[contentArray valueForKeyPath:#"#min.x"] floatValue];
result.maxY = [[contentArray valueForKeyPath:#"#max.y"] floatValue];
result.minY = [[contentArray valueForKeyPath:#"#min.y"] floatValue];
return result;
}
You can find max and min values when you fill it, but it would work just when used in your snippet. If you want something more generic you should simply go through the list and searching for it.
// contentArray already defined
int maxX = 0, minX = 1000, maxY = 0, minY = 1000;
for (int i = 0; i < [contentArray count]; ++1)
{
int curX = [[[contentArray objectForKey:#"x"] objectAtIndex:i] integerValue];
int curY = [[[contentArray objectForKey:#"y"] objectAtIndex:i] integerValue];
if (curX < minX)
minX = curX;
else if (curX > maxX)
maxX = curX;
if (curY < minY)
minY = curY;
else if (curY > maxY)
maxY = curY;
}
You could use fast enumeration through the array.
.
NSUInteger maxX = 0;
NSUInteger minX = 0xFFFFFFFF; //(for 32 bit)
NSUInteger maxY = 0;
NSUInteger minY = 0xFFFFFFFF; //(for 32 bit)
for ( NSDictionary *dict in contentArray )
{
NSUInteger newX = [[dict objectForKey:#"x"] integerValue];
NSUInteger newY = [[dict objectForKey:#"y"] integerValue];
if (maxX > newX) maxX = newX;
if (minX > newX) minX = newX;
if (maxY > newY) maxY = newY;
if (minY > newY) minX = newY;
}
if you have NSMutableArray of NSDictionary objects you can use this:
-(float)findMax:array arrayKey:obj {
float max = [[[array objectAtIndex:0] objectForKey:obj] floatValue];
for ( NSDictionary *dict in array ) {
if(max<[[dict objectForKey:obj] floatValue])max=[[dict objectForKey:obj] floatValue];
}
return max;
}
-(float)findMin:array arrayKey:obj {
float min = [[[array objectAtIndex:0] objectForKey:obj] floatValue];
for ( NSDictionary *dict in array ) {
if (min > [[dict objectForKey:obj] floatValue])min = [[dict objectForKey:obj] floatValue];
}
return min;
}
You would access methods like this if in another class:
GraphData *c=[[GraphData alloc] init];
float maxY=[c findMax:plotData arrayKey:[NSNumber numberWithInt:1]]; //1 or 0 depending on axis
[c release];
//This gives Max and Min Value in NSMutableArrray
-(void)FindingMinAndMaxValueInNSMutableArray{
NSMutableArray *array=[[NSMutableArray alloc]initWithObjects:#"0.987",#"0.951",#"0.881",#"0.784",#"0.662",#"0.522",#"0.381",#"-0.265",#"-0.197", #"0.189",#"-0.233",#"0.310",#"0.402",#"0.402",#"0.988",#"0.633",#"0.661",#"0.656",#"0.617",#"0.634",#"0.690",#"0.767",#"0.836",nil];
NSLog(#"The Array Value is %#",array);
NSLog(#"The Array Count is %lu",(unsigned long)array.count);
NSNumber *maxValue = [array valueForKeyPath:#"#max.doubleValue"];
NSLog(#"The maxValue is %#",maxValue);
NSString *str=[NSString stringWithFormat:#"%#",maxValue];
NSInteger path=[array indexOfObject:str];
NSIndexPath *indexpath=[NSIndexPath indexPathForItem:path inSection:0];
NSLog(#"Max Value = %# and index = %ld",maxValue,(long)indexpath.row);
NSNumber *minValue = [array valueForKeyPath:#"#min.doubleValue"];
NSLog(#"The minValue is %#",minValue);
NSString *str1 = [NSString stringWithFormat:#"%#",minValue];
NSInteger path1 = [array indexOfObject:str1];
NSIndexPath *indexPath1 = [NSIndexPath indexPathForItem:path1 inSection:0];
NSLog(#"Min Value =%# and index = %ld",minValue,(long)indexPath1.row);
}