有没有oop高手,实在是黔驴技穷了
查看原帖
有没有oop高手,实在是黔驴技穷了
555584
weiming3楼主2023/2/27 15:49

一开始用oop写,输出有问题而且不好改,模仿思路写了个简洁点的c,还是WA

#include <iostream>
#include <string>
#include <math.h>
using namespace std;
int len(int n) {
	if (n == 0) {
		return 1;
	}
	int count = 0;
	if (n < 0) {
		count++;
	}
	while (n) {
		count++;
		n /= 10;
	}
	return count;
}
int transform(string s) {
	int ans = 0;
	for(int i=0;i<=s.length()-1;i++){
		ans+=(int)(pow(10,i))*(s[s.length()-1-i]-'0') ;	
		
	}
	return ans;
}
int main() {
	string a[55][5];
	int b[55][5];
	int n;
	cin >> n;
	char mark;
	for (int i = 1; i <= n; i++) {
		string s;
		cin >> s;
		if (isalpha(s[0])) {
			mark = s[0];
			b[i][1] = mark - '0';
			for (int j = 1; j <= 2; j++) {
				cin >> a[i][j];
				b[i][j + 1] = transform(a[i][j]);
			}
		} else {
			b[i][1] = mark - '0';
			a[i][1] = s;
			b[i][2] = transform(s);
			cin >> a[i][2];
			b[i][3] = transform(a[i][2]);
		}
	}
	for (int i = 1; i <= n; i++) {
		if (b[i][1] == '+' - '0') {
			cout << b[i][2] << "+" << b[i][3] << "=" << b[i][2] + b[i][3] << endl;
			cout << len(b[i][2]) + b[i][3] + len(b[i][2] + b[i][3]) + 2 << endl;
		}
		if (b[i][1] == '-' - '0') {
			cout << b[i][2] << "-" << b[i][3] << "=" << b[i][2] - b[i][3] << endl;
			cout << len(b[i][2]) + len(b[i][3]) + len(b[i][2] - b[i][3]) + 2 << endl;
		}
		if (b[i][1] == '*' - '0') {
			cout << b[i][2] << "*" << b[i][3] << "=" << b[i][2]*b[i][3] << endl;
			cout << len(b[i][2]) + b[i][3] + len(b[i][2]*b[i][3]) + 2 << endl;
		}
	}
	return 0;
}

输出只有一个return 0,不知道cout的内容给谁吞了 问了chatgpt,隔靴挠痒 please check other bug There are a few issues with the modified code:

In the len function, when n is negative, you are not handling the - sign correctly. You need to remove the sign before counting the number of digits. Change count++; to n = abs(n); count++; to fix this.

In the main function, you are not initializing the mark variable. You need to move the cin >> s; line outside the if-else block and assign the first character of s to mark.

In the first if block of the for loop, you are using j <= 2 instead of j < 2. This will cause the loop to run 3 times instead of 2, resulting in undefined behavior.

In the len function, you are not accounting for the additional characters (+, -, *) and = that will be printed. You need to add 4 to the total length.

2023/2/27 15:49
加载中...