gpt4 book ai didi

ios - 为我的计算器添加小数点

转载 作者:行者123 更新时间:2023-11-29 12:35:33 26 4
gpt4 key购买 nike

我正在尝试制作一个计算器。一切正常,但现在我想添加一个小数点,但我不知道如何添加。你能帮忙吗?谢谢。

我试过了

- (IBAction) buttondecimal {
SelectNumber = SelectNumber * 10;
SelectNumber = SelectNumber + @".";
Screen.text = [NSString stringWithFormat: @"%0.f", SelectNumber]; }

,但我得到一个错误:二进制表达式的无效操作数('double' 和 'NSString *')

这是我的代码:

.h

#import <UIKit/UIKit.h>

int Method;
double SelectNumber;
double RunningTotal;

@interface KalkulackaViewController : UIViewController
{
IBOutlet UILabel *deglabel;
IBOutlet UIButton *degbutton;
IBOutlet UITextField *Screen;
}

-(IBAction)Number1:(id)sender;
-(IBAction)Nasobeni:(id)sender;
-(IBAction)Deleni:(id)sender;
-(IBAction)Minus:(id)sender;
-(IBAction)Plus:(id)sender;
-(IBAction)Rovnase:(id)sender;
-(IBAction)AllClear:(id)sender;

@end

.m

#import "KalkulackaViewController.h"

@interface KalkulackaViewController ()

@end

@implementation KalkulackaViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];

UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10,10)];
Screen.rightView = paddingView;
Screen.rightViewMode = UITextFieldViewModeAlways;
Screen.leftView = paddingView;
Screen.leftViewMode = UITextFieldViewModeAlways;
}
-(IBAction)Number1:(id)sender
{
SelectNumber = SelectNumber * 10;
SelectNumber = SelectNumber + 1;
Screen.text = [NSString stringWithFormat:@"%0.f", SelectNumber];
}
- (IBAction) buttondecimal
{

}

最佳答案

SelectNumberdouble ,您不能像使用 @"." 那样向其添加字符串.

您最有可能要做的就是将值存储在字符串中(而不是在 SelectNumber 中)。例如,如果您在计算器中添加数字“1”:

Screen.text = [Screen.text stringByAppendingString:@"1"];

小数点也是如此(尽管您应该检查它是否已经包含小数点):

if ([screen.text rangeOfString:@"."].location == NSNotFound) {
screen.text = [screen.text stringByAppendingString:@"."];
}

然后,要从字符串中获取值以进行实际计算,您只需使用doubleValue即可。 :

double value = [screen.text doubleValue];

如果您愿意,这样做还可以让您添加退格键:

if (screen.text.length > 0) {
screen.text = [screen.text substringToIndex:screen.text.length - 1];
}

此外,旁注:您不应以大写字母开头命名变量。 Camelcase 是 Objective-C 的标准(并且被普遍接受)。示例:runningTotal , selectNumber .函数名等也是如此,主要是大写字母开头的一般都是类名,这样可以提高可读性,减少混淆。

关于ios - 为我的计算器添加小数点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26442643/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com