gpt4 book ai didi

c - 我的双变量的输出值在 Arduino Uno 上不正确

转载 作者:行者123 更新时间:2023-11-30 20:35:48 25 4
gpt4 key购买 nike

我使用此代码来测试当我打印双变量时输出是否会正确显示:

double t = (0.8*0.8*(10^5)*599*(10^-6)*1388.888889)/(287*(25+273)*14.7*3*(10^-3)*4);
Serial.println(t);

但是我在串口上的输出是4.03而不是3.52

我使用的是 Arduino UNO 和 Arduino C 语言。

我的代码有什么问题?

最佳答案

how could I solve this problem

在 C、C++、JavaScript、Java 中:

数字 10^5 必须在程序中表示为 1e5

数字 10^-6 为 1e-6

使用“^”强制程序执行按位运算 10^5 = (10)^(5)

参见:https://msdn.microsoft.com/en-us/library/3akey979.aspx

解决方案

改变

double t = (0.8*0.8*(10^5)*599*(10^-6)*1388.888889)/(287*(25+273)*14.7*3*(10^-3)*4);

致:

double t = (0.8*0.8*(1e5)*599*(1e-6)*1388.888889)/(287*(25+273)*14.7*3*(1e-3)*4);

现在你得到了正确的结果:

t = 3.5292104651726235

arduino 上的 int 范围非常有限:32767 到 -32768。长值为 2147483647 到 -2147483648

避免混合 int 和 double 以避免舍入错误。

仅使用 double 或者您可以使用强制转换:

 double d = (double)(0.8*0.8*(1e5)*(double)599*(1e-6)*1388.888889)/(((double)287)*((double)(‌​25+273))*((14.7*((double)3)))*(1e-3)*(double)4);

关于 Arduino 的注意事项

Serial.print(1.23456); //gives "1.23"

要获取更多数字,请将 double 变量转换为字符串并打印字符串。

示例:

double num = (double)(0.8*0.8*(1e5)*(double)599*(1e-6)*1388.888889)/(((double)287)*((double)(25+273))*((14.7*((double)3)))*(1e-3)*(double)4);
char output[50];

snprintf(output, 50, "%f", num);

Serial.print(output); // should give you at least 3.529210

关于c - 我的双变量的输出值在 Arduino Uno 上不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37758512/

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