我有一个问题,C的一些内置函数。基本上,我试图创建的是我自己的colpitts振荡器计算器,它接受以下输入作为参数:电感值,电容值,第二个电容值。
输入可以以F或H结尾,也可以有前缀p、m、n和u来表示pico、milli、nano和micro。如果数字太大,还将对输出进行格式化,并在其后面附加一个后缀。
在插入debug printf语句后,我的程序遇到的问题是数字转换不正确。
我按如下顺序使用了测试参数:
1p 2pF 3F这是我的初始输出:
DEBUG Init proc: 1p
DEBUG post proc: 0.000000
DEBUG Init proc: 2p
DEBUG post proc: 0.000000
DEBUG Init proc: 3
DEBUG post proc: 3.000000但是,除最后一行外,DEBUG post proc行都是错误的。
我想看看:
DEBUG Init proc: 1p
DEBUG post proc: 0.000000000001
DEBUG Init proc: 2p
DEBUG post proc: 0.000000000002
DEBUG Init proc: 3
DEBUG post proc: 3.000000这是我的代码:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main(int argc,char* argv[]){
if (argc < 4){
printf("Need 3 args: L, C1, C2. %d supplied\n",argc-1);return -1;
}
long double nums[4],f;long isnum;
int n=0;
for (n=1;n<4;n++){
//process each arg
char *p=argv[n];while(*p != '\0'){p++;};p--;
//strip last character if it's F, f, H, or h
if (*p=='F' || *p=='f' || *p=='H' || *p=='h'){*p='\0';p--;}
printf("DEBUG Init proc: %s\n",argv[n]);
switch (*p){
case '0': //do nothing if new last character is a number
break;
case 'p': //convert picounit to unit
*p='\0';
nums[n]=strtoll(argv[n],NULL,10)/1000000000000ULL;
break;
case 'n': //convert nanounit to unit
*p='\0';
nums[n]=strtoll(argv[n],NULL,10)/1000000000ULL;
break;
case 'u'://convert microunit to unit
*p='\0';
nums[n]=strtoll(argv[n],NULL,10)/1000000ULL;
break;
case 'm'://convert milliunit to unit
*p='\0';
nums[n]=strtoll(argv[n],NULL,10)/1000ULL;
break;
default: //do nothing if new last character is a number from 1 to 9 or print error if it isn't u,m,n or p.
isnum=strtol(p,NULL,10);
if (isnum < 1 || isnum > 9 || isnum=='\0'){
printf("Number %d is in bad format. Use suffix of either: uH mH nH pH uF mF nF pF\n",n);
return -1;
}
nums[n]=strtoll(argv[n],NULL,10);
}
printf("DEBUG post proc: %Lf\n",nums[n]);
}
printf("Input values: %Lf,%Lf,%Lf\n",nums[1],nums[2],nums[3]);
//calculate frequency
f=1/(2*3.14159)*sqrt(nums[1]*((nums[2]*nums[3])/(nums[2]+nums[3])));
char suf=' '; //prepare suffix to display frequency in user friendly format
if (f > 1000000){f=f/1000000;suf='M';} //convert to Mhz if f > 1000000
if (suf=='\0' && f > 1000){f=f/1000;suf='K';}
printf("Frequency = %Lf %c hz\n",f,suf);
return 0;
}因为我只使用32位处理器,所以我觉得我对这个问题的回答是有限的。我能做些什么来纠正这个问题?
发布于 2017-05-08 06:47:44
首先,正如Evert所提到的,你是在做整数除法。编写nums[n]=strtoll(argv[n],NULL,10)/(1000000000000.0);或nums[n]=((double)strtoll(argv[n],NULL,10))/1000000000000ULL应该可以解决这个问题。
一旦你的数字是正确的,输出可能会四舍五入到小数点后第六位:
C99§7.19.6.1 The C99 function,
f,F
在样式[−]ddd.ddd中,表示浮点数的double参数将转换为小数表示法,其中小数点字符后的位数等于精度规范。如果精度缺失,则取6; .
编写printf("DEBUG post proc: %1.15Lf\n",nums[n]),您应该会看到其余部分。
https://stackoverflow.com/questions/43837469
复制相似问题