2011-10-04 59 views
2

我会尽可能具体.. 我有这样的代码:简化和重写我的代码

// bintodec.cpp : Defines the entry point for the console application. 

#include "stdafx.h" 
#include <iostream> 
#include <string> 

using namespace std; 

int main(){ 
    string inp; 
    int dec = 0; 
    char base; 
    cout << "Input a number: "; 
    cin >> inp; 
    cout << "Input the base your number is in: "; 
    cin >> base; 
    for (int i = inp.length()-1, j = 0; i >= 0; i--, ++j) 
     dec += (inp[i]-48) * pow((float)base-48, j); 
    cout << "Your number in base 10 is: " << dec <<endl; 
    system("pause"); 
    return 0; 
} 

我试图重写/简化IT..to:

{ 
    int j=0,x; 
    double dec,y; 
    for(int i = inp.length()-1; i >= 0; i--) 
    { 
    x=(inp[i]-48); 
    y=pow((float)base-48, j); 
    dec=dec + x * y; 
    ++j; 
    } 
} 

我有:

int j=0,x; 
    double dec, y; 
     char base, inp; 

     cout << "Input a number: "; 
    cin >> inp; 
    cout << "Input the base your number is in: "; 
    cin >> base; 


     { 
      for (int i = inp.length()-1; i>=0; --i) 
      x=(inp[i]-48); 
      y=pow((float)base-48, j); 
      dec=dec + (x*y) 
       ++j; 
      { 
      return 0; 

出于某种原因,它不是working..visual工作室报道说:

  1. “长度”的左侧必须具有类/结构/联合类型是‘字符’
  2. 下标要求数组或指针类型
  3. ‘++’需要-1-值
  4. 语法错误:缺少';'标识符'j'前

我想重写和简化它..帮助错误请..谢谢!

+1

这是功课? – SpeedBirdNine

+0

即时通讯猜测你问的问题是hw是识别错误..没有它不是 –

+0

我问这是这个作业,所以它的作业是我可以添加一个作业标签到您的问题 – SpeedBirdNine

回答

6

1:您不能做inp.length(),因为您将inp声明为char。而一个字符不是一个字符串。

尝试声明inp作为string

string inp; 

2: “下标要求数组或指针型”

同上原因。 inp是一个char而不是数组或字符串。

3/4: “ '+' 需要L值”

你失踪分号:dec=dec + (x*y)

+0

我也使用字符串基地? TY! –

+0

不需要,你应该使用:'char base;'(这是正确的方式) – Mysticial

+0

你确定base是好的吗?它不需要用'base - ='0'来纠正';'? –