c - 在用户输入旁边打印输出

标签 c printf scanf

根据问题,用户需要输入车辆停放的小时数,并且旁边应打印小时的总费用。

例如:

enter image description here

我创建了这个简单的程序

#include<stdio.h>>
#include<math.h>

float calculateCharges(float hurs);
int main()
{
    float hours;//total no of hours vehicle is parked
    int i;

    printf("%s%10s%10s", "Car", "Hours", "Charges");
    
    for (i = 1; i <= 3; i++)
    {
        printf("\n%d\t", i);
        scanf("%f", &hours);
        printf("\t%f\n", calculateCharges(hours));
    }




    getch();
    return 0;
}


float calculateCharges(float hurs)
{

    float charges;

    hurs = ceil(hurs);

    if (hurs >= 24) charges = 10; 
    else
    {
        if (hurs <= 3) charges = 2;
        else
        {
            hurs = hurs - 3;
            charges = 2 + 0.5*hurs;

        }

    }

    return charges;
}
 

但现在每次我输入小时数时,费用都会打印在它下面而不是旁边。如图所示:

enter image description here

有没有办法在scanf之后消费换行符?这样费用就可以打印在scanf旁边了?

我也用这种方式修改了我的代码,但没有任何区别。

printf("%s%10s%10s", "Car", "Hours", "Charges");
    
    for (i = 1; i <= 3; i++)
    {
        printf("\n%d\t", i);
        printf("\t%f\n",(scanf("%f", &hours),calculateCharges(hours)));
    }

如果需要原始问题,请告诉我。我正在使用 Visual Studio 2017 RC。

最佳答案

你可以这样使用:

#include <iostream>
#include <windows.h>

//This will set the position of the cursor
void gotoXY(int x, int y) {
    //Initialize the coordinates
    COORD coord = {x, y};
    //Set the position
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
    return;
}

void getCursorXY(int &x, int&y) {
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    if(GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) {
        x = csbi.dwCursorPosition.X;
        y = csbi.dwCursorPosition.Y;

    }
}

我找到了 here . 正如其中一个答案中所写,该解决方案平台独立。

但我想其他平台上也有类似的解决方案,您可以轻松地将光标设置在您想要的位置。

在你的主要用法示例:

for (i = 1; i <= 3; i++)
{
    printf("\n%d\t", i);
    scanf("%f", &hours);
    gotoXY( 20, i + 1);
    printf("\t%f\n", calculateCharges(hours));
}

可以找到 scanf 的解决方法 here .

关于c - 在用户输入旁边打印输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41674109/

相关文章:

C 中点圆算法 将圆分成 4 个

C: 简单复制输入 (getchar) 到输出 (printf) 返回额外的行

c - 读取以逗号分隔的字符串

c - 为什么当我读取这个文件并扫描 int 时,输出的数字非常大?

c - Arduino 程序资源不足

c++ - snprintf : Same code - different errors/warnings on different g++ compilers

c - 将括号 ("(") 放在 printf 代码中有什么问题

c - printf ("%d") 不显示我输入的内容

c - 使用 fscanf() 读取一行

将 C 程序转换为 MIPS