c++ - For 循环不按公式输出正确的结果

标签 c++

我正在尝试完成 C++ 类(class)的作业。问题如下

Create a C-program that prints two columns on the screen with the temperature in degrees Fahrenheit and the equivalent temperature in degrees Celsius.

The left column shows the temperature in Fahrenheit. The right column shows the temperature in Celsius.

Start with 0 degrees Fahrenheit and proceed until 300 degrees Fahrenheit. Take steps of 20 degrees. Print degrees Celsius with 1 position behind the comma (use “%10.1f” as format specifier). Also print a header text.

Make the program maintenance insensitive, which means that the start- and end-temperature and the step size must be easy to adjust.

这是我的C++代码

{
    // TEMPERATURE CONVERSION
    float celsius;
    float startrange;
    float endrange;
    float increment;

    printf("Enter start range in Fahrenheit \n");
    scanf("%f",&startrange);
    printf("Enter end range in Fahrenheit \n");
    scanf("%f",&endrange);
    printf("Enter increments in Fahrenheit \n");
    scanf("%f",&increment);

    float counter;

    for(counter=startrange; counter<endrange; counter = counter + increment)
    {
        celsius=(5.0/9.0)*(counter-32);
        printf("%f \t","%f \n",counter,celsius);
    }
    return 0;
}

CMD 屏幕输出只为所有结果打印 0。不确定我的方法有什么问题 - 我将用户输入的值分配给输入,循环应该只打印输出。

我得到的错误在截图中:

https://imgur.com/a/kEEdiSD

最佳答案

您的 printf 调用使用 "%f\t" 作为格式说明符,并传递字符串文字 "%f\n" 作为要格式化的值。因此程序表现出未定义的行为,因为 %f 说明符需要类型为 double 的参数,而不是 char*

第三个和第四个参数——实际的浮点值——根本没有任何对应的格式说明符。

关于c++ - For 循环不按公式输出正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51698834/

相关文章:

C++完全删除(或重置)结构的所有值?

c++ - 为什么 const_cast 不修改调用函数中的值?

c++ - 我可以假设兄弟类的静态转换将无法编译吗?

c++ - 传递参数为 `const` 的奇怪效果

c++ - 如何在 MFC 应用程序退出时设置错误级别

C++ vector 元组,按索引从元素创建元组

c++ - 检查 char 数组中前导字符的最快方法是什么?

c++ - F.54 : If you capture this, 显式捕获所有变量(没有默认捕获)

c++ - 轻松更改 GlobalVariable 的类型

c++ - 在 C++ 中使用 cin 时使用循环计数被忽略