gpt4 book ai didi

c - 如何根据传感器读数动态打印字符串

转载 作者:行者123 更新时间:2023-11-30 21:14:32 25 4
gpt4 key购买 nike

在我的程序中,我只是从传感器读取风向。我在打印英文版本的说明时遇到问题。基本算法是这样的:

(值以度为单位,从结构中读取)

string direction;  (I know you have to create a char array, just not sure how)

if(sensor.windir > 11 && sensor.windspeed < 34)
{
direction = "NNE";
}

if(sensor.windir > 34 && sensor.windspeed < 57)
{
direction = "NE";
}



.....


printf(" Current windir is %s\n", direction);

我对 C 很生疏,需要复习一下如何根据“if”语句中定义的值范围来打印风向字符串。我的字符串中不需要超过 3 个字符。

最佳答案

首先你应该包括string.h使用strcpy功能:

#include <string.h>

您可以像这样声明 char 数组:

char direction[4]; //4 char array (4th is the NULL string terminator)

而不是 direction = "NE";direction = "NNE";你应该使用strcpy :

strcpy(direction, "NE");
strcpy(direction, "NNE");

所以你的程序看起来像这样:

#include <string.h>

char direction[4];

if(sensor.windspeed > 11 && sensor.windspeed < 34)
{
strcpy(direction, "NNE");
}

if(sensor.windspeed > 34 && sensor.windspeed < 57)
{
strcpy(direction, "NE");
}
printf("%s", direction);

如果您想节省一个字节的内存,您可以动态地执行此操作:

#include <string.h>

char *direction;

if(sensor.windspeed > 11 && sensor.windspeed < 34)
{
if(!(direction = malloc(4))) //4 for NULL string terminator
{
/*allocation failed*/
}
strcpy(direction, "NNE");
}

if(sensor.windspeed > 34 && sensor.windspeed < 57)
{
if(!(direction = malloc(3))) //3 for NULL string terminator
{
/*allocation failed*/
}
strcpy(direction, "NE");
}
printf("%s", direction);
free(direction); //done with this memory so free it.

关于c - 如何根据传感器读数动态打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12477629/

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