gpt4 book ai didi

cocoa - 在 Cocoa 的不同函数中保留随机数?

转载 作者:行者123 更新时间:2023-12-03 17:00:44 27 4
gpt4 key购买 nike

我知道如何创建全局变量,但是每当我尝试使用随机数函数定义全局变量时,xcode 都会显示“初始化元素不是常量”。编译器不想从随机数创建变量,因为随机数函数不是常数。

如何生成一个随机数,然后将同一值用于多个操作? (例如,定义颜色然后将该值写入标签?)

代码:

#import "Slider_with_IBAppDelegate.h"

float * const hue = ((arc4random() % ((unsigned)100 + 1))/100.0);

//^this is where I get the error: "initializer element is not constant"

@synthesize label

//write value to label
- (IBAction) doButton {
label.text = [NSString stringWithFormat:@"%f", hue];
}

//set background color
- (void)applicationDidBecomeActive:(UIApplication*)application
{
self.label5.backgroundColor = [UIColor colorWithHue:hue
saturation:1.0
brightness:1.0
alpha:1.0];
}

----编辑------

感谢您的建议。但它仍然对我不起作用,我做错了什么?

新代码:

#import "Slider_with_IBAppDelegate.h"

float const hue = ((arc4random() % ((unsigned)100 + 1))/100.0);

//^I still get the error: "initializer element is not constant."

@synthesize label

//write value to label
- (IBAction) doButton {
label.text = [NSString stringWithFormat:@"%f", hue];
}
//^this is where I get the error "'hue' undeclared (first use of this function)"

//set background color
- (void)applicationDidBecomeActive:(UIApplication*)application
{

hue = ((arc4random() % ((unsigned)1000 + 1))/1000.0);
/*here I get the error "assignment of read-only variable 'hue.'"
If I insert "float" just before hue, I do not get this error,
but it still won't compile because of the error above.*/

self.label5.backgroundColor = [UIColor colorWithHue:hue
saturation:1.0
brightness:1.0
alpha:1.0];
}

最佳答案

将其设为非常量并在 applicationDidBecomeActive 中对其进行初始化。有什么理由它必须保持不变吗?

关于cocoa - 在 Cocoa 的不同函数中保留随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1060171/

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