[英]Function not giving a valid output (C on Visual Studio 2010)
我已經嘗試自動執行與電子學相關的演算。 不幸的是,我的代碼似乎無法正常工作,因為所有結果均為0.000000(請參見下文)。
這是我嘗試的方法:-使用double或int變量-刪除微積分部分,並嘗試從輸入中獲取輸出-scanf_s和scan_f。
這些都不起作用。 奇怪的是,最后的printf甚至無法打印base_v(例如)。
這是代碼本身:
#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
int _tmain(int argc, _TCHAR* argv[])
{
// variable declaration
double base_r, mod_r, base_v, mod_v=0;
double coeff=1;
int asdf=1;
// welcome message
printf("vMod calculator\n");
printf("Please enter resistances in Ohms and voltages in Volts\n");
// retrieve info about vmod
printf("Enter base resistance\n");
scanf_s("%f", &base_r);
printf("Enter modified resistance\n");
scanf_s("%f", &mod_r);
printf("Enter base voltage\n");
scanf_s("%f", &base_v);
// calculus of modified voltage
coeff=asdf*((1/base_r)+(1/mod_r));
mod_v=base_v*base_r*coeff;
// results
printf("Base voltage: %f \n", &base_v);
printf("Base resistance: %f \n", &base_r);
printf("Modified voltage: %f \n", &mod_v);
printf("Modified resistance: %f \n", &mod_r);
system("pause");
return 0;
}
如果您不了解演算,請參考下圖: http : //pbrd.co/1g6KWLp
謝謝
您正在傳遞printf
參數&base_v
的地址,而不是其值base_v
。 簡而言之,擺脫&
printf("Base voltage: %f \n", base_v);
printf("Base resistance: %f \n", base_r);
printf("Modified voltage: %f \n", mod_v);
printf("Modified resistance: %f \n", mod_r);
首先,您將指針打印為浮點數,因此具有未定義的行為 。
printf
直接采用變量,而不是其地址:
printf("Base voltage: %f \n", base_v);
printf("Base resistance: %f \n", base_r);
printf("Modified voltage: %f \n", mod_v);
printf("Modified resistance: %f \n", mod_r);
scanf在第一次調用后將stline緩沖區中的換行符0x13和0x10留在stdin緩沖區中,因此對於dos / windows,下一次調用將首先獲得13/10,請先使用fgets,再使用fscanf或while((dumchar = getch())== \\ n)之類的東西; 在每個scanf()調用之前清除換行符
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.