【问题标题】:multiply int with data input in textfield result in label将 int 与文本字段中的数据输入相乘得到标签
【发布时间】:2014-03-04 05:46:20
【问题描述】:

int Bonus = .3(需要百分比,这等于 30%)

label = (textfield * Bonus)

Objective-C 新手,如果需要更多说明,请随时待命。

更新:已解决!解决方案:

这里是 .h 文件:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController {

 IBOutlet UILabel *label;
 IBOutlet UITextField *textfield;
}


- (IBAction)save:(id)sender;

@end

这是.m文件

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController





- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)save:(id) sender {

    float x = ([textfield.text floatValue]);
    float bonus = .3;
    float result;
    result = x * bonus / 10; 

// Divide by 10 to keep it percentage based




    label.text = [[NSString alloc] initWithFormat:@"%.2f", result];

感谢大家的帮助!尤其是许音!!

【问题讨论】:

  • 每当您在stackoverflow上寻求答案时,您都需要添加更多信息。
  • 上次我被告知我必须提供很多信息,但不是直截了当....
  • int Bonus 更改为 float Bonus 否则您的结果将始终为 0。

标签: objective-c uitextfield int uilabel decimal


【解决方案1】:

我同意pacman321,也许下次尝试添加更多信息..

看起来你的问题是:

//1.> "convert NSString to number" 
float value = [textfield.text floatValue];

//2.> do the math 
value = value * Bonus; //Could also be value *= Bonus;

//3.> Convert number back to NSString
label.text = [NSString stringWithFormat:@"%f", value];

我认为这就是你所需要的,但这里有一些建议:确保你的文本字段只有数值。并且可能需要注意要在标签中显示多少位数。

【讨论】:

  • 仅供参考-第二行可以简单地是value *= Bonus;
  • @rmaddy 你是对的,我的可能对他来说更容易理解,但我会将你的答案添加到我的答案中。谢谢!
  • 谢谢,你能看看我的更新我还有问题吗?
  • @Ouch 你使用 int 而不是 float 作为奖励,int 会忽略小数位,所以在这种情况下你的 0.3 --> 0。
  • 是的,我明白了 :) 谢谢。不过我有一个问题,我没有看到它实际上显示了总结果?我需要指定一些方法吗?
【解决方案2】:

这里都解释过了https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Strings/Articles/FormatStrings.html

textfield.text = [NSString stringWithFormat:@"%d%%", Bonus * 100]

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-07
  • 1970-01-01
相关资源
最近更新 更多