【发布时间】:2018-12-16 16:48:11
【问题描述】:
我在C中有这两个变量:
double predict_label = 6.0;
double prob_estimates = 8.0;
如何将C 中的这两个变量转换为char 并打印出类似“预测标签的值为6,概率估计的值为8”的字符串。
【问题讨论】:
标签: c type-conversion printf
我在C中有这两个变量:
double predict_label = 6.0;
double prob_estimates = 8.0;
如何将C 中的这两个变量转换为char 并打印出类似“预测标签的值为6,概率估计的值为8”的字符串。
【问题讨论】:
标签: c type-conversion printf
您可以安排将没有小数位(因此没有小数点)的浮点值打印到字符串变量中,然后可以根据需要将其打印到文件中——例如使用snprintf()。该代码还使用字符串连接来避免过长的行。
#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;
}
【讨论】:
如果您真的想将变量值添加到字符串中,可以使用 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);
}
【讨论】:
我认为您不想转换为字符,而是想打印的整数值。假设,这应该足够了:
printf("predict label is %d and probability estimates is %d\n",
(int)predict_label, (int)prob_estimates);
【讨论】: