欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

7-4 复数的实部和虚部(8 分)

程序员文章站 2022-06-07 09:58:01
...

通常用一个形如”a+bi”的字符串来表示一个复数,a为复数的实部,b为复数的虚部。现在需要对输入的字符串进行分离,自动识别该复数的实部和虚部,并独立输出。

例如,对于输入的复数字符串“3-4.05i”,输出

complex 3-4.05i

the real part is 3

and the imaginary part is -4.05

注意:

1、用于表示复数的字符串符合数学上的书写习惯。

2、每组测试数据仅包括一个用于表示复数的字符串。

3、输入保证合法。


输入示例:

-4.567+3.987i

输出示例:

complex -4.567+3.987i

the real part is -4.567

and the imaginary part is 3.987


“输入保证合法”还是有几个小坑的:

1、实部为0;

2、虚部为0;

3、直接输0.


下面给出我的代码,欢迎斧正(有点麻烦,有待优化)

7-4 复数的实部和虚部(8 分)


#include <iostream>
#include <cstdio>
using namespace std;

int main()
{
    string complex;
	cin>>complex;
	if(complex[complex.length()-1]!='i')//判断输入的复数虚部是否为0,只需判断末尾字符有无"i"
	{
		cout<<"complex "<<complex<<endl<<"the real part is "<<complex<<endl;
		cout<<"and the imaginary part is 0";
		return 0;
	}
	int flag = 0;
	for(int i=1;complex[i];i++)//判断输入的复数实部是否为0,转化为判断字符中有无"+"/"-"
		if(complex[i]=='+'||complex[i]=='-')
		{
			flag = 1;
			break;
		}
	if(flag==0)
	{
		cout<<"complex "<<complex<<endl<<"the real part is 0"<<endl;
		cout<<"and the imaginary part is ";
		if(complex[0]=='i')
			cout<<"1";
		else if(complex[0]=='-'&&complex[1]=='i')
			cout<<"-1";
		else
			for(int i=0;i<complex.length()-1;i++)
				cout<<complex[i];

		return 0;
	}

	//正常情况下实部虚部的提取
    char real[100] = {0},imag[100] = {0};
    real[0] = complex[0];//把最开始的正负号避开
    int i = 1;
    while(1)//以"+"、"-" 为结尾提取实部
    {
        if(complex[i]=='+'||complex[i]=='-') break;
        real[i] = complex[i];
		i++;
    }
    int j = 0;
    while(1)//以"i"结尾提取虚部
    {
    	if(complex[i]=='i')break;
        imag[j++] = complex[i++];
    }
    cout<<"complex "<<complex<<endl<<"the real part is "<<real<<endl;
    cout<<"and the imaginary part is ";
	if(imag[0]=='+'&&imag[1]=='\0')
		printf("1");
	else if(imag[0]=='-'&&imag[1]=='\0')
		printf("-1");
	else if(imag[0]=='+')
		printf("%s",imag+1);
	else
		printf("%s",imag);
}

相关标签: pta