根据问题,用户需要输入车辆停放的小时数,并且旁边应打印小时的总费用。
例如:
我创建了这个简单的程序
#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;
}
但现在每次我输入小时数时,费用都会打印在它下面而不是旁边。如图所示:
有没有办法在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/