【问题标题】:In C, convert 2 doubles to form one character string在 C 中,将 2 个双精度数转换为一个字符串
【发布时间】: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


    【解决方案1】:

    您可以安排将没有小数位(因此没有小数点)的浮点值打印到字符串变量中,然后可以根据需要将其打印到文件中——例如使用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;
    }
    

    【讨论】:

    • 您好,请问使用缓冲区的目的是什么?
    • 该问题或多或少提到了转换为字符串。目前还不清楚需要什么。这是一种方法;直接写是另一回事。这取决于上下文。
    【解决方案2】:

    如果您真的想将变量值添加到字符串中,可以使用 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);
    }
    

    【讨论】:

    • 您好,请问使用缓冲区的目的是什么?
    【解决方案3】:

    我认为您不想转换为字符,而是想打印的整数值。假设,这应该足够了:

    printf("predict label is %d and probability estimates is %d\n",
           (int)predict_label, (int)prob_estimates);
    

    【讨论】:

      猜你喜欢
      • 2013-10-10
      • 2015-04-10
      • 1970-01-01
      • 2012-07-09
      • 2022-01-20
      • 1970-01-01
      • 2014-01-01
      相关资源
      最近更新 更多