[英]Why is this code not producing an output?
我正在編寫一個簡單的程序來顯示兩個會聚列車之間的距離/時間。 我想測試程序並通過函數 float 收斂返回輸出值,然后將其應用到主函數,但收斂函數似乎不起作用。
#include <stdio.h>
float converge(int x, int y, int z) {
return x / (y + z);
}
int main(void) {
int dist, speed1, speed2;
printf("Enter distance in miles");
scanf("%d\n", &dist);
printf("Enter train 1 speed and train 2 speed in mph");
scanf("%d%d\n", &speed1, &speed2);
converge(dist, speed1, speed2);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
float converge (float x, float y, float z)
{
int time=x/(y+z);
return time;
}
int main ()
{
float dist, speed1, speed2;
printf("Enter distance in miles:\t");
scanf("%f", &dist);
printf("Enter speed of first train in mph:\t");
scanf("%f", &speed1);
printf("Enter speed of second train in mph:\t");
scanf("%f", &speed2);
printf("Time between this two trains is %f",converge(dist, speed1, speed2));
}
為什么這段代碼不產生輸出?
由於提供的代碼中沒有可能導致此輸出的語句,因此它不會從converge()
的結果中產生預期輸出的輸出。
例如,您需要在調用converge()
之后使用一個printf()
語句來打印converge()
的結果:
#include <stdio.h>
float converge (int x, int y, int z)
{
return x/(y+z);
}
int main (void)
{
int dist, speed1, speed2;
float converge_result;
printf("Enter the distance between the two trains in miles:\n");
scanf("%d", &dist);
printf("\n");
printf("Enter the speed of train 1 and the speed of train 2 in mph:\n");
scanf("%d %d", &speed1,&speed2);
printf("\n");
converge_result = converge(dist, speed1, speed2);
printf("The time until the two trains encounter each other is:\n %f",converge_result);
return 0;
}
或者:
#include <stdio.h>
float converge (int x, int y, int z)
{
return x/(y+z);
}
int main (void)
{
int dist, speed1, speed2;
printf("Enter the distance between the two trains in miles:\n");
scanf("%d", &dist);
printf("\n");
printf("Enter the speed of train 1 and the speed of train 2 in mph:\n");
scanf("%d %d", &speed1,&speed2);
printf("\n");
printf("The time until the two trains encounter each other is: \n%f ",
converge(dist,speed1,speed2);
return 0;
}
順便說一句,時間距離的計算似乎不正確或至少不完整。
您的代碼中有多個問題:
converge
執行整數算術並將結果轉換為float
僅用於返回值。 如果你想計算一個小數,你應該把它改成: double converge(int x, int y, int z) { return (double)x / ((double)y + z); }
double converge(int x, int y, int z) { return (double)x / ((double)y + z); }
或更好的使用double
的輸入值和參數類型:
double converge(double x, double y, double z) { return x / (y + z); }
scanf()
轉換格式中有尾隨換行符:這將導致scanf()
消耗在數字之后鍵入的任何尾隨空格,包括在提示中鍵入的任意數量的換行符。 只要您輸入空行,您就不會收到第二個提示。 從格式字符串中刪除這些\\n
。
不打印計算結果。
這是一個修改后的版本:
#include <stdio.h>
double converge(double x, double y, double z) {
return x / (y + z);
}
int main(void) {
double dist = 0, speed1 = 0, speed2 = 0;
printf("Enter distance in miles: ");
scanf("%lf", &dist);
printf("Enter train 1 speed and train 2 speeds in mph: ");
scanf("%lf%lf", &speed1, &speed2);
if (speed1 + speed2 <= 0)
printf("No collision\n");
else
printf("Time until collision: %f seconds\", 3600 * converge(dist, speed1, speed2));
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.