在C语言中,将两个双精度字符转换成一个字符串

在C语言中,将两个双精度字符转换成一个字符串,c,type-conversion,printf,C,Type Conversion,Printf,我在C中有这两个变量: double predict_label = 6.0; double prob_estimates = 8.0; 如何将C中的这两个变量转换为char并打印出一个字符串,该字符串表示“预测标签的值为6,概率估计的值为8”。我认为您不想转换为char,而是想打印的整数值。假设这样,这就足够了: printf("predict label is %d and probability estimates is %d\n", (int)predict_label,

我在
C
中有这两个变量:

double predict_label = 6.0;
double prob_estimates = 8.0;
如何将
C
中的这两个变量转换为
char
并打印出一个字符串,该字符串表示“预测标签的值为6,概率估计的值为8”。

我认为您不想转换为char,而是想打印的整数值。假设这样,这就足够了:

printf("predict label is %d and probability estimates is %d\n",
       (int)predict_label, (int)prob_estimates);
如果确实要将变量值添加到字符串中,可以使用snprintf()

#define BUF_LEN 100

int main(void)
{
    char str[BUF_LEN];
    double predict_label = 6.0;
    double prob_estimates = 8.0;

    snprintf(str, BUF_LEN, "The value for predict label is %d and the value for probability estimates is %d.",
        (int)predict_label, (int)prob_estimates);

    printf("%s\n", str);
}

您可以安排将没有小数点的浮点值(因此也没有小数点)打印到字符串变量中,然后该字符串变量可以按照您的意愿打印到文件中,例如使用。代码还使用字符串连接来避免过长的行

#include <stdio.h>

int main(void)
{
    double predict_label = 6.0;
    double prob_estimates = 8.0;
    char buffer[256];

    snprintf(buffer, sizeof(buffer), 
             "The value for predict label is %.0f"
             " and the value for probability estimates is %.0f.",
             predict_label, prob_estimates);

    printf("%s\n", buffer);

    return 0;
}
#包括
内部主(空)
{
双预测_标签=6.0;
双概率估计=8.0;
字符缓冲区[256];
snprintf(缓冲区),sizeof(缓冲区),
“预测标签的值为%.0f”
“概率估计值为%.0f。”,
预测(标签、概率估计);
printf(“%s\n”,缓冲区);
返回0;
}

Hi,我可以知道使用缓冲区的目的是什么吗?Hi,我可以知道使用缓冲区的目的是什么吗?这个问题或多或少提到转换为字符串。不清楚需要什么。这是一种方法;直接写作是另一回事。这取决于上下文。