//
// ViewController.swift
// SimpleCalculator
//
// Created by ChenQianPing on 16/4/10.
// Copyright © 2016年 ChenQianPing. All rights reserved.
//
import UIKit
class ViewController: UIViewController
{
@IBOutlet weak var display: UILabel!
// 用户是不是已经输入
var userIsInTheMiddleOfTypingANumber:Bool = false
@IBAction func appendDigit(sender: UIButton) {
// Swift是非常强类型的语言
// Swift有一个非常强大的特性,叫做类型推导
let digit = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber{
// 可选值(Optional)是不可以拼接字符串的,所以在这个地方,需要进行解包
display.text = display.text! + digit
} else{
display.text = digit
userIsInTheMiddleOfTypingANumber = true
}
print("digit = \(digit)")
}
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber
{
enter()
}
// 除数是栈中的最后一个元素,而除数是栈中最先弹出的元素
switch operation {
case "×": performOperation { $0 * $1}
case "÷": performOperation { $1 / $0}
case "+": performOperation { $0 + $1}
case "−": performOperation { $1 - $0}
case "√": performOperation { sqrt($0)}
default:break
}
}
// 函数的参数是一个函数
func performOperation(operation:(Double,Double) -> Double){
if operandStack.count >= 2{
displayValue = operation(operandStack.removeLast(),operandStack.removeLast())
enter()
}
}
// 一个名字下的两个不同功能的函数,swift会自动识别应该用哪个函数的
private func performOperation(operation:Double -> Double){
if operandStack.count >= 1{
displayValue = operation(operandStack.removeLast())
enter()
}
}
// 这个变量是一个内部的栈,去存储你输入的这些数,他的类型是一个数组,这个数组里存放的是Double的变量,注意在这个地方要初始化.(我们不能使用没有经过初始化的,会报错)
// var operandStack: Array<Double> = Array<Double>()
var operandStack = Array<Double>()
@IBAction func enter() {
userIsInTheMiddleOfTypingANumber = false
operandStack.append(displayValue)
print("operandStack = \(operandStack)")
}
var displayValue:Double{
get{
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
}
set{
display.text = "\(newValue)"
userIsInTheMiddleOfTypingANumber = false
}
}
}
相关推荐
云服务器安装ros教程
要在 CentOS 7 系统上安装 RouterOS,您需要将 RouterOS 安装为虚拟机或直接安装到物理硬盘上。这里提供的是将 RouterOS 安装到物理硬盘上的步骤,这将完全替换现有的 CentOS 7 系统。请确保您已经备份了所有重要数据。
Swift语法中关于"!"和"?"的解析
在具体的操作前添加!符号,好吧,这又是什么诡异的语法?! let digit = sender.currentTitle! 这里的!表示“我确定这里的的strValue一定是非nil的,尽情调用吧” ,例如 if userIsInTheMiddleOfTypingANumber { //== true display.text = display.
直线型一阶倒立摆1---从理论到实践的桥梁
本文深入探讨了直线型一阶倒立摆在控制理论中的核心地位,从非线性控制、鲁棒性到实时反馈等关键问题。通过实际案例和硬件搭建指南,帮助读者理解从理论到实践的过渡,特别适合控制工程初学者和研究人员。文章还提供了算法选型建议和硬件避坑手册,是掌握倒立摆控制的实用指南。
一个简单的计算器,使用swift练习项目,模仿iPhone界面
先看效果:刚刚练习swift,代码比oc精简不少,不过有的地方还是不太习惯,尤其是里面需要判断的地方 无论何时都不能值为空,需要用可选类型,加上?和!,接着努力代码:class ViewController: UIViewController { let calResult = UILabel()//用来显示输入和结果的label,在最上方 var frontNum = Stri...
ubuntu 24.04安装ros1 noetic
上面是参考链接给的修改内容。除了上面要修改的地方,我在编译的生活还有一个地方报错,修改成如下形式。因为我已经对文件rosconsole_log4cxx.cpp作了上面的修改,所有是不是188行不太确认了,如果报“log4cxx::spi::LocationInfo”问题,按照下面修改就可以了。我在编译时还报了一个问题,就是我之前安装的是jazzy。所以在编译时会报ros变量名不对,这时对变量名做修改就可以了。具体怎么修改,百度。a、将源文件中所有CMakelist中编译标准改为c++ 17.
从零到一:Gromacs伞形采样的实战避坑指南
本文详细介绍了Gromacs伞形采样技术的实战应用与避坑指南,涵盖核心原理、环境准备、参数设置、数据分析及性能优化等关键环节。特别针对蛋白质-配体结合自由能计算等典型应用场景,提供了弹簧常数设置、采样窗口间距等实用参数建议,帮助研究人员高效完成分子动力学模拟。
currentTitle的用法
UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom]; [but setTitle:@"测试一下" forState:UIControlStateNormal]; NSLog(@"****%@",[button currentTitle]);//button.currentTitle NSLog(@"***...
LabVIEW状态机实战:用STM32+DHT11搭建温湿度监测系统(附完整VI源码)
本文详细介绍了如何利用LabVIEW状态机模式与STM32微控制器、DHT11温湿度传感器构建温湿度监测系统。通过硬件选型、状态机设计、LabVIEW程序实现及系统优化等环节,提供了一套完整的解决方案,并附有VI源码,助力开发者快速实现嵌入式温湿度监测应用。
iphone中Button的currentTitle和titleLabel.text的使用
UIButton *btn = [UIButtonbuttonWithType:UIButtonTypeCustom]; 1、[btn setTitle:@"测试一下" forState:UIControlStateNormal]; 输出:CurrentTitleLabel:测试一下,currentTitle:测试一下。模拟器button上显示:测试一下 2、btn.titlelabel.t...
Ubuntu 22.04远程桌面终极指南:从零配置RDP到解决黑屏问题
本文提供了一份Ubuntu 22.04远程桌面配置的终极指南,详细讲解了如何从零开始安装和配置RDP服务,并重点解决了连接后常见的黑屏问题。通过分析会话冲突、修复启动脚本及配置权限策略,帮助用户实现稳定、高效的远程桌面连接,优化分辨率、禁用锁屏,打造无缝的远程工作体验。
基于Python的农业市场价格抓取与供需分析:现代爬虫技术与实战应用
在正式开始爬虫开发之前,我们首先了解爬虫的基本概念和工作原理。爬虫(Web Scraping)是通过编程的方式,自动从互联网上获取信息的技术。它可以帮助我们提取HTML页面中的特定数据,通常用于收集并处理大量信息。发送HTTP请求:爬虫需要向目标网站发送请求,获取网站的HTML页面内容。解析HTML页面:通过HTML解析器对获取的页面内容进行解析,提取其中需要的数据。数据清洗与存储:将提取的数据进行清洗,去除多余的字符或无关内容,然后存储到合适的格式(如CSV文件、数据库等)中。数据分析与可视化。
01、Swift基础运算
01、Swift基础运算变量和常量变量常量Type Inference / annotation数据类型整数整数类型整数的常用表达方式浮点数和数字有关的类型推断(Type Inference)字符串获取前缀获取后缀遍历字符串中的每一个字符插入内容基于Range的查找和替换截取子串分割字符串字符串数组转换为字符串元组 Tuple定义元组访问元组元素元素比较常用操作符赋值操作基本算术运算操作符复合运算操作符比较操作符逻辑运算符 变量和常量 变量 在Swift里面,使用var来定义各种不同类型的变量: var n
DMA engine initialization failed rk3568的原因及解决方案
刚开始调试 switch 芯片的时候由于rgmii 时钟是output , rk3568的 GMAC 需要 switch 芯片提供 125M的时钟,如果没有这个时钟就会初始化失败,进入文件系统后 ethx 不会出现(当然,如果屏蔽掉这里ethx 会出现,但是引发更多的问题,笔者在这块耍小聪明,导致耗费了近一个月时间,把网络这块整个查了一遍 -----)dma 软复位是在进入文件系统后,网络系统启动的时候,我想如果在这个之前只要提供合适的时钟那么就是可以的,那么------以上是官方的文档说明。
01-Swift 基础
Swift 基础语法
efm32 入门.pdf
本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。
NTscan扫描工具
ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。
swift课程 01 swift 基础
打印print(arr1) //会自动换行 print("num: \(num1) age:\(age)") //嵌套输出,\(变量名)类似于printf("%d",num1)1.标注数据类型 变量或常量的具体类型修饰符放在名称后面,中间用‘:’隔开 eg:var biaozhu1: String = "name" //字符串 前不用@ var biaiozhu2: Int = 122
win10 跳过U8环境检测的IE WebControls.rar
win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。
Swift基础01
Swift基础01常量和变量的定义 用 var 来定义一个变量,用 let 定义一个常量 变量或常量的后面接一个 : Int, 指定数据类型 在 swift 中,布尔值用的是 true/false var a: Int = 5 //定义一个Int型变量 var b: Float = 6 var c: Double = 5.6 var d: Bool = true //布尔值 var e: Bo
深度学习工具包 DeepLearningToolbox
深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[](https://bitdeli.com/free "Bitdeli Badge")
Swift 教程之UIStackview 01 基础使用
Swift 教程之UIStackview 01 基础使用 请点击,免费订阅《学Swift挣美元》专栏 简介 UIStackView是支持线性流式界面布局集合视图,他支持column和row两种方向。UIStackView依托于Auto Layout的强大布局功能呢,可以根据不同设备方向、屏幕大小、容器大小来实现动态界面布局。 UIStackView通过...
Swift 基础01 —— Objective-C转战Swift
目录Swift 初体验常量&变量数据类型简单介绍类型推导基本运算逻辑分支if…else 的使用guard 的使用switch 分支循环使用for 循环while/ repeat while 循环 Swift 初体验 // 1.Swift导入框架 /* Objective-C #import <UIKit/UIkit.h> ----------------------------...
Playground -swift01基础学习
//: Playground - noun: a place where people can play // // test1.swift // swift02 // // Created by 张建 on 16/9/23. // Copyright © 2016年 zhangjian. All rights reserved. // import UIKit var str = "
Swift 01-基础语法
Hello World Playground - View Playground - ViewController Playground – 多Page 注释 Markup语法 ##链接 *百度 百度 常量 标识符 常见数据类型 字面量 类型转换 元组(Tuple)
Swift基础学习01
相关网站:http://www.cnblogs.com/tt_mc/p/3871295.html 相关辅助操作: 可以在右边直接查看输出值 可能出现的常见问题: 1.凡是=注意左右间距一样 2.程序有时会不断提示错误,解决方法:重启Xcode /*-----------1.常量与变量--------------*/ //1.在swift里面 变...
Swift基础知识_01
import Foundation // 1.介绍swift的特点 // a.语句结束后可以不用加分号 // b.访问对象的属性和方法都用点语法 // 2.变量和常量 // a.常量用 "let"关键字修饰,不可修改 let num1 = 12 // b.变量用 "var"关键字修饰,可以修改 var num2 = 3 num2 = 6 print("
Swift 教程之TableView使用01基础代码
请点击,免费订阅《学Swift挣美元》专栏 之前介绍过了如何通过Storyboard来使用tableview,个人感觉还是非常快速和高效的。不过在实际开发过程中,使用代码来创建tableview是十分必要的。因此本系列将带领大家从零开始学习如何使用代码来应用tableview。 Swift 教程之TableView使用01基础代码 1. 注册一下c...
芒果iOS开发之Swift教程01-Swift基础
苹果在2014年WWDC(苹果开发者大会)发布了Swift,用于编写iOS,Mac OS X和watchOS应用程序。Swift 采用安全的编程模式并添加了很多新特性,而且对于熟悉OC人开发者来说学习Swift也很简单。是不是已经迫不及待要体验Swift了。
01-Swift基础语法
// 第一节:// 1.导入框架// 框架和头文件 直接import就行了import UIKit// 2.定义一个标识符// swift中定义标识符:必须制定该标识符是一个常量还是一个变量// var(变量)/let(常量) 标识符的名称 : 标识符的类型 = 初始化值var a : Int = 10; // Int类型不能赋值Double类型的值var b : ...
01-swift-基础语法了解
函数类型 格式: 函数类型:(Int Int)->Int,即:参数类型 + 返回值类型 用途:可以作为函数的返回值或者参数 func jia(num1: Int, num2: Int) -> Int { return num1 + num2; } MARK: - 枚举 enum Direction : String { case east = "东" case norst = "西" case souce = "南" case wast = "北"
2145



被折叠的 条评论
为什么被折叠?



